Skip to content

Map Location Input Question

In Aliveforms, custom properties and logic unit can be used to create a custom map location input screen. In this example we are going to use Leaflet for maps. This is very useful in situations like pick and drop location, order registration etc.

Set up

Let's say we want to have a map location question screen. So, on screen 0, we add custom property key map with value true.

  • map : true

Then we setup logic to handle these props.

Using Events

We can use event handling or special functions. If there are more than one logic units requiring special function on same screen, it is better to use $.Handle for those.

Inspector in our friend

Inspect elements to perform DOM manipulation.

Input Type: Execute JavaScript
Screen Index: -1
Execute JavaScript | -1
let frm = $.HackForm();
let cnt = frm.length

$.ImportStyle('https://unpkg.com/leaflet@1.9.4/dist/leaflet.css', function () {
  $.ImportScript('https://unpkg.com/leaflet@1.9.4/dist/leaflet.js', function () {
    init()
  })
})

function init() {
  for (let i = 0; i < cnt; i++) {
    if (frm[i]?.customProps?.map) {
      $.Handle(`screen_${i}_on_enter`, function () {
        $.Alert('map added to ' + i)
        setTimeout(function() {
          mapIt(i)
        }, 300)
      });
    }
  }
}

function mapIt(i) {
  let c = (document.querySelector('.options_wrapper'));
  let od = document.createElement('div');
  od.id = 'map'
  od.style.height = "400px";
  (document.querySelector('#ti')).style.opacity = '0';
  c.appendChild(od);
  var map = L.map(c).fitWorld();
  L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 19,
    attribution: '© OpenStreetMap'
  }).addTo(map);
  map.locate({ setView: true, maxZoom: 16 });

  var popup = L.popup();

  function onMapClick(e) {
    popup
      .setLatLng(e.latlng)
      .setContent("You clicked the map at " + e.latlng.toString())
      .openOn(map);

    $.HackInputs(i, e.latlng.toString());
  }

  map.on('click', onMapClick);

  function onLocationFound(e) {
    var radius = e.accuracy;

    L.marker(e.latlng).addTo(map)
      .bindPopup("You are within " + radius + " meters from this point").openPopup();

    L.circle(e.latlng, radius).addTo(map);
    $.HackInputs(i, e.latlng.toString());

  }
  function onLocationError(e) {
    alert(e.message);
  }

  map.on('locationerror', onLocationError);
  map.on('locationfound', onLocationFound);

}