Google Maps API - 获取最接近邮政编码的点 [英] Google Maps API - Getting closest points to zipcode

查看:118
本文介绍了Google Maps API - 获取最接近邮政编码的点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,感谢您花时间考虑我的问题并寻求您的帮助。



我正在使用Google为网站添加地图Maps API v3和javascript。



我有地址列表,并已成功在地图上绘制它们。当用户键入邮政编码时,地图会重新显示其位置,并显示与该点最接近的标记。现在,我需要为他们的邮政编码创建一个最近的3个或5个位置的列表视图,并提供关于驾驶方向的链接。



谢谢!

解决方案

通常的解决方案是使用 google.maps.geometry.spherical库 computeDistanceBetween(from:LatLng,to:LatLng,radius?:number)方法将数量减少到大约10,然后使用距离矩阵返回到这些位置的行车距离,因此可以按驾驶距离(实际行驶距离)对结果进行排序,并通过实际行程减少到最接近的3到5个位置请求范围内的距离。

示例(查找列表中距离列表最近的3个地点)
(从FusionTablespizza store示例中借用的数据)
$ b $ pre $ function codeAddress(){
var address = document.getElementById('address')。value;
geocoder.geocode({'address':address},function(results,status){
if(status == google.maps.GeocoderStatus.OK){
map.setCenter(results (0).geometry.location);
if(customerMarker)customerMarker.setMap(null);
customerMarker = new google.maps.Marker({
map:map,
position:results [0] .geometry.location
});
nearest = findClosestN(results [0] .geometry.location,10);
//获得行车距离
最接近= nearest.splice(0,3);
calculateDistances(results [0] .geometry.location,closest,3);
} else {
alert('Geocode was not successful for原因如下:'+ status';
}
});
}

函数findClosestN(pt,numberOfResults){
var closest = [];
document.getElementById('info')。innerHTML + =processing+ gmarkers.length +< br>;
for(var i = 0; i gmarkers [i] .distance = google.maps.geometry.spherical.computeDistanceBetween(pt,gmarkers [i] .getPosition( ));
document.getElementById('info')。innerHTML + =process+ i +:+ gmarkers [i] .getPosition()。toUrlValue(6)+:+ gmarkers [i] .distance。 toFixed(2)+ <峰; br> 中;
gmarkers [i] .setMap(null);
closest.push(gmarkers [i]);
}
closest.sort(sortByDist);
回报最接近;


函数sortByDist(a,b){
return(a.distance- b.distance)
}

函数calculateDistances (pt,closest,numberOfResults){
var service = new google.maps.DistanceMatrixService();
var request = {
origins:[pt],
destinations:[],
travelMode:google.maps.TravelMode.DRIVING,
unitSystem:google.maps .UnitSystem.METRIC,
avoidHighways:false,
avoidTolls:false
};
for(var i = 0; i< closest.length; i ++)request.destinations.push(closest [i] .getPosition());
service.getDistanceMatrix(request,function(response,status){
if(status!= google.maps.DistanceMatrixStatus.OK){
alert('Error was:'+ status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('side_bar');
outputDiv .innerHTML ='';

var results = response.rows [0] .elements;
for(var i = 0; i< numberOfResults; i ++){
closest [i] .setMap(map);
outputDiv.innerHTML + =< a href ='javascript:google.maps.event.trigger(closest [+ i +],\click \ );'>+ closest [i] .title +'< / a>< br>'+ closest [i] .address +< br>
+ results [i] .distance。 text +'appoximately'
+ results [i] .duration.text +'< br>< hr>;
}
}
});
}

上面的例子与infoWindow中的获取路线链接


First off, thanks for taking the time to consider my question and for your help.

I'm in the process of adding a map to a website using Google Maps API v3 and javascript.

I have a list of addresses and have successfully plotted them on the map. When the user types in a zip code, the map re-centers on their location showing the markers closest to that point. Now, I need to create a list view of the closest 3 or 5 locations to their zip code with links for driving direction. I'm stuck...and open for suggestions.

Thanks!

解决方案

The usual solution is to use the google.maps.geometry.spherical library computeDistanceBetween(from:LatLng, to:LatLng, radius?:number) method to reduce the number to about 10, then use the distance matrix return the driving distance to those locations so the results can be sorted by driving distance (actual travel distance), and reduced to the closest 3 to 5 locations by actual travel distance within the request limits.

example (finds the 3 closest places from a list) (data borrowed from the FusionTables "pizza store" example)

  function codeAddress() {
    var address = document.getElementById('address').value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
    if (customerMarker) customerMarker.setMap(null);
        customerMarker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
    closest = findClosestN(results[0].geometry.location,10);
        // get driving distance
        closest = closest.splice(0,3);
        calculateDistances(results[0].geometry.location, closest,3);
      } else {
        alert('Geocode was not successful for the following reason: ' + status);
      }
    });
  }

function findClosestN(pt,numberOfResults) {
   var closest = [];
   document.getElementById('info').innerHTML += "processing "+gmarkers.length+"<br>";
   for (var i=0; i<gmarkers.length;i++) {
     gmarkers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt,gmarkers[i].getPosition());
     document.getElementById('info').innerHTML += "process "+i+":"+gmarkers[i].getPosition().toUrlValue(6)+":"+gmarkers[i].distance.toFixed(2)+"<br>";
     gmarkers[i].setMap(null);
     closest.push(gmarkers[i]);
   }
   closest.sort(sortByDist);
   return closest;
}

function sortByDist(a,b) {
   return (a.distance- b.distance)
}

function calculateDistances(pt,closest,numberOfResults) {
  var service = new google.maps.DistanceMatrixService();
  var request =    {
      origins: [pt],
      destinations: [],
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.METRIC,
      avoidHighways: false,
      avoidTolls: false
    };
  for (var i=0; i<closest.length; i++) request.destinations.push(closest[i].getPosition());
  service.getDistanceMatrix(request, function (response, status) {
    if (status != google.maps.DistanceMatrixStatus.OK) {
      alert('Error was: ' + status);
    } else {
      var origins = response.originAddresses;
      var destinations = response.destinationAddresses;
      var outputDiv = document.getElementById('side_bar');
      outputDiv.innerHTML = '';

      var results = response.rows[0].elements;
      for (var i = 0; i < numberOfResults; i++) {
        closest[i].setMap(map);
        outputDiv.innerHTML += "<a href='javascript:google.maps.event.trigger(closest["+i+"],\"click\");'>"+closest[i].title + '</a><br>' + closest[i].address+"<br>"
            + results[i].distance.text + ' appoximately '
            + results[i].duration.text + '<br><hr>';
      }
    }
  });
}

example above with "Get Directions" link in the infoWindow

这篇关于Google Maps API - 获取最接近邮政编码的点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆