如何在Google地图路线

时间:2015-07-28 20:31:30

标签: google-maps google-maps-api-3

如何在谷歌地图上获取娱乐,食品,加油站等所有地方,只在不在附近的路线上绘制从源到目的地的路线。

1 个答案:

答案 0 :(得分:0)

To build on the link that @geocodezip gave, to work around query limits it might be a better practice to make a bounding box based on steps rather than using the Google Maps utility, and then filter locations by actual distance to a node in the step. This could be accomplished using the following code:

In initialize(), put:

var placeserv = null;
function initialize(){
  //setup map
  placeserv = new google.maps.PlacesService(map); //use your map variable
}

In the callback function for the Directions Service (using parameters results and status), you can include something like this:

var route = results[0];
var steps = route.legs[0].steps;
for(var i=0; i<steps.length; i++){
  var lats = steps[i].path.map(function(a){return a.lat()});
  var lngs = steps[i].path.map(function(a){return a.lng()});
  var box = new google.maps.LatLngBounds(
    new google.maps.LatLng(Math.max.apply(null, lats), Math.max.apply(null, lngs)),
    new google.maps.LatLng(Math.min.apply(null, lats), Math.min.apply(null, lngs))
  );
  placeserv.radarSearch(yourRequest_seeDocumentation_or_geocodezipsCode,
    function(r,s){callback(r,s,steps[i].path)}
  );
  //depending on the number of queries you need to make, you may to add in
  //some setTimeouts
}

And then add a callback function for your call that checks if the route is within a specified degree. If so, it will do something with the location. (By the way, this requires the Geometry Library for Google Maps. Please look it up.)

var minimumDist = 300 //within 300 meters of a point on the route
function callback(results, status, stepPts){
  if(results == 'OK'){
    for(var j=0; j<results.length; j++){
      for(var k=0; k<stepPts.length; k++){
        var dist = google.maps.geometry.spherical.computeDistanceBetween(stepPts[k], results[j].geometry.location);
        if(dist < minimumDist){
          //do something with the location
        }
      }
    }
  }
}

Again, geocodezip has a very complete and excellent post in the link he gave you. This is just the implementation I would use to cut down on Places Service calls.