Google Maps API - Radius search for markers using Places?

断了今生、忘了曾经 提交于 2019-12-02 17:21:37

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

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