2013-04-22 78 views
0

我想弄清楚兩個谷歌地圖圈(標記周圍)相交或彼此碰撞時可能發現的情況。谷歌地圖API圓相交檢測

我想完成的是,如果兩個圓相交,我想提出一個事件。我不確定這是否可能。

回答

0

計算圓心的距離,如果它小於兩個圓的半徑之和,則它們相交。

0

下面是一些JavaScript,將檢測如果兩個圓相交

var e = Math;   // shortcut for the mathematical function 
var D2R = e.PI/180.0; // value used for converting degrees to radians 

Number.prototype.toRadians = function() { 
    return this * D2R; 
}; 

function distance(lat0,lng0,lat1,lng1){ 

    // convert degrees to radians 
    var rlat0 = lat0.toRadians(); 
    var rlng0 = lng0.toRadians(); 
    var rlat1 = lat1.toRadians(); 
    var rlng1 = lng1.toRadians(); 

    // calculate the differences for both latitude and longitude (the deltas) 
    var Δlat=(rlat1-rlat0); 
    var Δlng=(rlng1-rlng0); 

    // calculate the great use haversine formula to calculate great-circle distance between two points 
    var a = e.pow(e.sin(Δlat/2),2) + e.pow(e.sin(Δlng/2),2)*e.cos(rlat0)*e.cos(rlat1); 
    var c = 2*e.asin(e.sqrt(a)); 
    var d = c * 6378137; // multiply by the radius of the great-circle (average radius of the earth in meters) 

    return d; 
} 

    function hasIntersections(circle0,circle1){ 
    var center0 = circle0.getCenter(); 
    var center1 = circle1.getCenter(); 

    var maxDist = circle0.getRadius()+circle1.getRadius(); 
    var actualDist = distance(center0.lat(),center0.lng(),center1.lat(),center1.lng()); 

    return maxDist>=actualDist; 
    } 

只需調用與引用到自己的圈子hasIntersections。下面是一個示例,顯示兩個幾乎接觸的圓圈(返回false),並且如果您將c1中的零更改爲一個圓圈,它們將觸摸(返回true)。

map = new google.maps.Map(document.getElementById('map'), { 
     center: {lat: 41.081301, lng: -98.214219}, 
     zoom: 25 
    }); 

    var c0 = new google.maps.Circle({ 
     strokeOpacity: .1, 
     strokeWeight: 1, 
     fillColor: '#0000FF', 
     fillOpacity: .2, 
     map: map, 
     center: {lat:41.082953, lng: -98.215285}, 
     radius: 200 
     }); 

    var c1 =new google.maps.Circle({ 
     strokeOpacity: .1, 
     strokeWeight: 1, 
     fillColor: '#FF0000', 
     fillOpacity: .2, 
     map: map, 
     center: {lat:41.081070, lng: -98.214027}, 
     radius: 34.692866520 
     }); 
     console.log(hasIntersections(c1,c0));