views:

161

answers:

1

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?

+2  A: 

You 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:

Daniel Vassallo
This method won't work. Some of the steps might be over 50km long (like when going along the same motorway). If my point of interest is half way up that step, checking if the point is within a 25km radius will give lots of false positives. I need to know if the point is exactly on that route or not.
Pavel
@Pavel: You're right. Check the updated answer. It had to iterate through the polyline vertices, and not through the route steps as I suggested earlier.
Daniel Vassallo