【问题标题】:Google Maps API - Getting closest points to zipcodeGoogle Maps API - 获取最接近邮政编码的点
【发布时间】:2013-06-21 06:33:42
【问题描述】:

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

我有一个地址列表,并已成功将它们绘制在地图上。当用户输入邮政编码时,地图会重新以他们的位置为中心,显示最接近该点的标记。现在,我需要创建一个列表视图,其中包含离他们的邮政编码最近的 3 或 5 个位置以及行车方向的链接。我被困住了……欢迎提出建议。

【问题讨论】:

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


    【解决方案1】:

    通常的解决方案是使用google.maps.geometry.spherical librarycomputeDistanceBetween(from:LatLng, to:LatLng, radius?:number) 方法将数字减少到10左右,然后使用distance matrix返回到这些位置的行驶距离因此可以将结果按行驶距离(实际行驶距离)排序,并在请求限制内按实际行驶距离减少到最近的 3 到 5 个位置。

    example (finds the 3 closest places from a list) (数据来自 FusionTables“披萨店”示例)

      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

    【讨论】:

      【解决方案2】:

      当您拥有邮政编码的 lat lng 对时,您可以使用 harversine 公式来查找到您所在位置的距离。

      【讨论】:

        猜你喜欢
        • 2011-11-28
        • 2011-07-31
        • 2017-02-15
        • 2018-01-03
        • 2011-04-11
        • 2021-06-08
        • 1970-01-01
        • 2011-05-19
        相关资源
        最近更新 更多