I'm ploting a route between two points and I need to check if the route goes through a predefiend location. In the api, each GStep has a start and end points but the path doesn't have to be straight. Given a Lat/Long point, is there a way to check if it intersects with a route?
views:
161answers:
1You should be able to get the individual vertices of the polyline generated by GDirections
very easily. First you have to make sure to pass the getPolyline: true
option when you call the GDirections.load()
if you do not attach the GDirections
to the map. Then you can simply iterate through each vertex of the polyline, and then you should probably check if your point is within a certain distance threshold from your predefined location.
Consider the following example:
var map = new GMap2(document.getElementById("map"));
var directions = new GDirections(map);
// Your predefined point
var pt = new GLatLng(51.470, -0.453);
directions.load('from: London, UK to: Glasgow, UK', { getPolyline: true });
GEvent.addListener(directions, "load", function() {
for (var i = 0; i < directions.getPolyline().getVertexCount(); i++) {
if (directions.getPolyline().getVertex(i).distanceFrom(pt) < 100) {
// Your predefined point is within 100 meters of the route
}
}
});
You could probably improve this method by skipping some steps that are definitely too far from your test point. You could get the polyline index of each route step with the getPolylineIndex()
method. This can help you restricting your for loop to a narrower set of vertices.
Further reading and reference: