5

I am bringing in leaflet routing control into my map and I would like to have the route icons show up in the center of the current view. using the code below I can get the icons to show up at the center of the inital view but I cannot find a way to get the center to update

Javascript:

    var route = L.Routing.control({
  waypoints: [
  L.latLng(map.getCenter()),
  L.latLng(map.getCenter())
  ]
});

JQuery:

$("#route-btn").click(function(event) {
  event.preventDefault();
  $('.leaflet-routing-container').is(':visible') ? route.removeFrom(map) : route.addTo(map);l
});

like most of the mistakes I make it is probably something simple, any help would be welcomed.

2
  • I'm having trouble understanding what you are asking. Are you talking about this plugin or a different one? And what are you trying to do exactly (what do you mean by current view, for example). Overall difficult to answer without more explanation, and more code. A complete example would be useful. – toms Jan 30 '15 at 16:37
  • I now see how unclear this request is. to clarify I am using the Leaflet Routing Machine plugin. when I fire getCenter, it adds points at the center of the initial view of the map. I would like the center to adjust based on where the user has moved the map to the new center of the map, not the original one. – dave_does_not_understand Jan 30 '15 at 17:06
4

Use map.getBounds() to obtain an LatLngBounds Object. This object has the method getCenter(), which will eventually give you an LatLng Object, which you can use for your purpose.

1

It seems like map.getCenter() is only being called when you first declare route, and the waypoints retain those values afterward. So when you use route.addTo(map) in your function, map.getCenter() is not actually called again to reset them. To update the waypoints, you can use the setWaypoints method:

route.setWaypoints([L.latLng(map.getCenter()), L.latLng(map.getCenter())]);

Here's an example fiddle with a button that resets both waypoints to the current map center:

http://jsfiddle.net/nathansnider/pu39s9wn/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.