[Google Map]以指定長度為半徑畫圖
八月 22, 2008
在電視電影中的連續犯罪事件,常常可以看到偵探或警方在地圖上以犯罪現場為中心依地緣關係畫出圓形而展開調查。
即然能用GPolygon畫出多邊形,加點小小的計算我們也能畫出圓形,而且是可以指定半徑距離(如5公里)的圓!
程式碼
google.load("maps", "2.x");
google.setOnLoadCallback(initialize);
var map = null;
function initialize() {
// 檢查瀏覽器是否可使用 Google Map API
if ( GBrowserIsCompatible() ) {
map = new google.maps.Map2(document.getElementById('map'));
// 設定地圖中心點
map.setCenter(new GLatLng(25.036772,121.520269), 10);
// 畫圓!
draw(5/*半徑,公里*/, 36/*以多少點畫圓*/);
} // if
else {
alert('您的瀏覽器不支援Google Map');
} // else
}
////pan and zoom to fit
var bounds = new GLatLngBounds();
function fit(){
map.panTo(bounds.getCenter());
map.setZoom(map.getBoundsZoomLevel(bounds));
}
//calling circle drawing function
function draw(givenRad, givenQuality){
map.clearOverlays();
bounds = new GLatLngBounds();
var centre = map.getCenter()
drawCircle(centre, givenRad, givenQuality);
fit();
}
////////////////////////// circle///////////////////////////////
function drawCircle(center, radius, nodes, liColor, liWidth, liOpa, fillColor, fillOpa)
{
// Esa 2006
//calculating km/degree
var latConv = center.distanceFrom(new GLatLng(center.lat()+0.1, center.lng()))/100;
var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng()+0.1))/100;
//Loop
var points = [];
var step = parseInt(360/nodes)||10;
for(var i=0; i<=360; i+=step)
{
var pint = new GLatLng(center.lat() + (radius/latConv * Math.cos(i * Math.PI/180)), center.lng() +
(radius/lngConv * Math.sin(i * Math.PI/180)));
points.push(pint);
bounds.extend(pint); //this is for fit function
}
fillColor = fillColor||liColor||"#0055ff";
liWidth = liWidth||2;
var poly = new GPolygon(points,liColor,liWidth,liOpa,fillColor,fillOpa);
map.addOverlay(poly);
}
[...] code sample above is found at this page (ESA), which also provides some other nice examples using the Google maps API here. Enjoy making your own [...]