How to get markers after calling directions in the Google Maps API?

I just started using the Google Maps API yesterday and tried to set directions to my map. My problem: when I call the function load,

// [...] gdir = new GDirections(map, directionsPanel); // [...] gdir.load("from: " + fromAddress + " to: " + toAddress); 

it returns a map whose markers are not dragged. Therefore, I need to make them draggable to recalculate routes, but I cannot get marker objects.

Does anyone know how I can do this?

+4
source share
1 answer

You need to add a GDirections object handler for the addoverlay event:

 GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay); 

When the onGDirectionsAddOverlay handler is called, you can iterate over new markers and replace them with dragged copies:

 for (var i = 0; i <= gdir.getNumRoutes(); i++) { var originalMarker = gdir.getMarker(i); latLngs[i] = originalMarker.getLatLng(); icons[i] = originalMarker.getIcon(); newMarkers[i] = new GMarker(latLngs[i], { icon: icons[i], draggable: true, title: 'Kan flyttes' }); map.addOverlay(newMarkers[i]); // add stuff to your newMarkers[i] drag end event... // ... //Bind 'click' event to original markers 'click' event copyClick(newMarkers[i], originalMarker); // Now we can remove the original marker safely map.removeOverlay(originalMarker); } 

You can find a working example of this here ( source ).

+2
source

Source: https://habr.com/ru/post/1303958/


All Articles