To use the class, create a SnapToRoute
object and pass
the GMap2
object and target GPolyline
and GMarker
objects to the constructor.
var map = new GMap2(document.getElementById("map")); map.setCenter(new GLatLng(37, -122), 13); var marker = new GMarker(map.getCenter()); map.addOverlay(marker); var polyline = new GPolyline([new GLatLng(37.1, -122.1), new GLatLng(37.2, -122.2)]); map.addOverlay(polyline); var snapToRoute = new SnapToRoute(map, marker, polyline);
This will make the marker snap to the polyline at all times.
It is also possible to get information about how far along the line
the current marker is. This can be done by calling the method
SnapToRoute.getDistAlongRoute()
. You can optionally
provide a GLatLng
object as a parameter to query a different point.
var distanceInMeters = snapToRoute.getDistAlongRoute(); var latlng = map.getCenter(); var distanceInMetersFromCenter = snapToRoute.getDistAlongRoute(latlng);
The following example shows one possible use for SnapToRoute. You can use the class to snap a looking glass (a marker with a custom icon) to a route. This way, you can allow the user to zoom to a detailed view of any point along the route. The code below shows the creation of the SnapToRoute
object:
createMarker(); createRoute(); snapToRoute = new SnapToRoute(map, lookingGlass, routeOverlay);
View example (detailzoom.html)
In this example, we let the user click the map to create a path, and then display the distance along the route for the marker in a status div.
You can also use the right mousebutton to click on the map to stop and restart the snapping.
The code below is called after a map click event. It either creates a new SnapToRoute
object if none exists, or it just updates the existing object with the changed line.
routeVertices.push(vertex); var pix = G_NORMAL_MAP.getProjection().fromLatLngToPixel(vertex, map.getZoom()); routePixels.push(pix); if (routeVertices.length > 1) { plotRoute(); if (!snapToRoute) { snapToRoute = new SnapToRoute(map, startMarker, routeOverlay); } else { snapToRoute.updateTargets(null, routeOverlay); } } else { startMarker = createMarker(vertex,'Start') map.addOverlay(startMarker); }
The code below is called after a mouse move event on the map. It displays the distance along the route in a DIV.
document.getElementById("statusDiv").innerHTML = snapToRoute.getDistAlongRoute().toFixed(0) + " meters from start at " + latlng.toUrlValue();
View example (demonstration.html)