Google Maps API - Radius search for markers using Places?

后端 未结 1 511
后悔当初
后悔当初 2021-01-31 12:47

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

相关标签:
1条回答
  • 2021-01-31 13:26

    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

    0 讨论(0)
提交回复
热议问题