简体   繁体   中英

Google Maps draw circle around radius search

I'm drawing a circle the size of the radius over which I'm performing a nearby search:

  // Point where to search  
  var searchArea = new google.maps.LatLng(25.435833800555567, -80.44189453125);

  // Draw a circle around the radius
  var circle = new google.maps.Circle({
    center: searchArea,
    radius: parseFloat(document.getElementById("distance").value) * 1609.3, //convert miles to meters
    strokeColor: "#0000FF",
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: "#0000FF",
    fillOpacity: 0.4
   });          
   circle.setMap(map);  

   // Perform search over radius
   var request = {
        location: searchArea,
        radius: parseFloat(document.getElementById("distance").value) * 1609.3, //convert miles to meters
        keyword: "coffee",
        rankBy: google.maps.places.RankBy.PROMINENCE
      };
      service.nearbySearch(request, callback);         
    }

I then plot markers. This works fine but in some cases markers show outside the circle leading me to believe that it might not be the same size as the radius.

Here is a very good example of what I mean.

http://jsfiddle.net/hnPRh/2/

Notice how markers show outside the circle. Why is this happening?

The way I would do it is to calculate the distance from the center point. I've set your radius into a variable called RADIUS , make sure to place it where it is executed after the document has loaded.

I've also modified your for loop to include distance check. The distance function accepts 2 arguments which are both of type google.maps.LatLng

var EARTH_RADIUS = 6378137; // meters
var RADIUS = (parseFloat(document.getElementById("distance").value) * 1609.3);

function deg2rad(deg) {
    return deg * (Math.PI / 180);
}

function distance(pos1, pos2) {
    var p1Lat = pos1.lat(),
        p1Lng = pos1.lng(),
        p2Lat = pos2.lat(),
        p2Lng = pos2.lng(),

        dLat = deg2rad(p1Lat-p2Lat),
        dLon = deg2rad(p1Lng-p2Lng),

        a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(deg2rad(p1Lat)) * Math.cos(deg2rad(p2Lat));

    return EARTH_RADIUS * (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)));
}



for (var i = 0; i < results.length; i++) {
    if (distance(results[i].geometry.location, searchArea) <= RADIUS) {
        createMarker(results[i]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM