Google Maps API - Radius search for markers using Places?

北城余情 提交于 2019-12-03 03:58:35

问题


I have set up a Google Map using API v3. The map has a number of markers with infoboxes attached. I am looking to set up a search box outside of the map for the user to input an address and then have the nearest markers returned based on the distance away (such as a radius search).

From the API documentation I think I need to uses the Places services. Can anyone point me in the right direction?


回答1:


To do a radius search with the API, use the Geometry Library google.maps.geometry.spherical.computeDistanceBetween method to calculate the distance between each marker and the geocoded result from the address. If that distance is less than the requested radius, show the marker, else hide it.

code assumes:

  1. array of google.maps.Markers called gmarkers
  2. google.maps.Map object called 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



来源:https://stackoverflow.com/questions/18364715/google-maps-api-radius-search-for-markers-using-places

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!