5

我已经使用API​​ v3建立了一个Google Map。地图上有许多附有信息框的标记。我正在寻找在地图之外设置搜索框以供用户输入地址,然后根据距离返回最近的标记(例如半径搜索)。Google Maps API - Radius使用Places来搜索标记?

从API文档,我想我需要使用的地方服务。任何人都可以将我指向正确的方向吗?

+0

您如果您正在查找结果,则需要使用Places API e Places API。如果您希望返回自己的标记,则需要使用Google Maps API v3实现该标记。 – geocodezip

+0

你现有的代码是什么样的? – geocodezip

回答

14

要使用API​​进行半径搜索,请使用Geometry Librarygoogle.maps.geometry.spherical.computeDistanceBetween方法来计算每个标记与地址的地理编码结果之间的距离。如果该距离小于请求的半径,请显示标记,否则将其隐藏。

代码假定:

  1. 阵列google.maps.Markers的称为gmarkers
  2. google.maps.Map对象调用地图

    function codeAddress() { 
        var address = document.getElementById('address').value; 
        var radius = parseInt(document.getElementById('radius').value, 10)*1000; 
        geocoder.geocode({ 'address': address}, function(results, status) { 
        if (status == google.maps.GeocoderStatus.OK) { 
         map.setCenter(results[0].geometry.location); 
         var marker = new google.maps.Marker({ 
         map: map, 
         position: results[0].geometry.location 
         }); 
         if (circle) circle.setMap(null); 
         circle = new google.maps.Circle({center:marker.getPosition(), 
                radius: radius, 
                fillOpacity: 0.35, 
                fillColor: "#FF0000", 
                map: map}); 
         var bounds = new google.maps.LatLngBounds(); 
         for (var i=0; i<gmarkers.length;i++) { 
         if (google.maps.geometry.spherical.computeDistanceBetween(gmarkers[i].getPosition(),marker.getPosition()) < radius) { 
          bounds.extend(gmarkers[i].getPosition()) 
          gmarkers[i].setMap(map); 
         } else { 
          gmarkers[i].setMap(null); 
         } 
         } 
         map.fitBounds(bounds); 
    
        } else { 
         alert('Geocode was not successful for the following reason: ' + status); 
        } 
        }); 
    } 
    

example