astaga
astaga

Reputation: 91

get coordinate from leaflet locate control

i try to extract user coordinate with locate control plugin to send it via ajax

var startMarker;
var lc = L.control.locate({
    position: "topright",
    layer: startMarker,
    drawCircle: false,
    showPopup: false,
    markerClass: L.marker,
  })
  .addTo(mymap);

when the marker appeared, i click to send startMarker layer coordinate via ajax with this code

$("button").on("click", (e) => {
  e.preventDefault();
  if (startMarker == null) {
    alert(`startpoint not defined`);
  } else {
    $.ajax({
      type: "POST",
      data: {
        startlat: startMarker.getLatLng().lat,
        startlng: startMarker.getLatLng().lng,
      },
      url: "php/find_nearest_path.php",
      dataType: "json",
      success: dosomething,
      error: function () {
        alert("failed getting respond from server");
      },
    });
  }
});

but the error i get is alert(`startpoint not defined`); anybody now the proper way to get the coordinate?

Upvotes: 0

Views: 1055

Answers (1)

ghybs
ghybs

Reputation: 53300

When you pass your startMarker variable to the layer option of L.control.locate (from leaflet-locatecontrol plugin), it is still undefined.

Therefore the plugin behaves as if you had not passed any value to that option. And its default behaviour in that case is to create its own internal Layer Group.

Since you seem to need to check on the created Marker once it is available, you simply need to assign a Layer Group to your variable before passing it to the option:

var startMarker = L.layerGroup();
var lc = L.control.locate({
    layer: startMarker,
  })
  .addTo(mymap);

Then in your condition, check if that Layer Group has a child Marker, instead of checking for an assignment:

var locationLayers = startMarker.getLayers();

if (locationLayers.length === 0) {
  alert(`startpoint not defined`);
} else {
  // Last position should be represented by one of the last layers
  // (there may be several layers on same position, should you
  // have enabled circle and/or compass)
  var positionMarker = locationLayers[locationLayers.length - 1];
  // Do something with positionMarker.getLatLng()...
}

That being said, as implicitly pointed out by Ivan in the question comments, since you seem to need the created Marker only to get the location coordinates, you could get thos from the locationfound event instead. That way, you would not need to retrieve any Marker.

Upvotes: 1

Related Questions