简体   繁体   English

Google地图围绕半径搜索绘制圆

[英]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/ 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. 我已将半径设置为一个名为RADIUS的变量,请确保将其放置在文档加载后要执行的位置。

I've also modified your for loop to include distance check. 我还修改了您的for循环以包括距离检查。 The distance function accepts 2 arguments which are both of type google.maps.LatLng distance函数接受两个均为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]);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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