2010-09-06 93 views
1

這是我的代碼:矩形範圍內的隨機標記?

function getRandom_marker(bounds) { 
    var leftBottom=[bounds.getSouthWest().lat(),bounds.getSouthWest().lng()] 
    var rightTop=[bounds.getNorthEast().lat(),bounds.getNorthEast().lng()] 
    var latlng=[leftBottom[0]+Math.floor(Math.random() * (rightTop[0]-leftBottom[0])), 
    leftBottom[1]+Math.floor(Math.random() * (rightTop[1]-leftBottom[1]))] 
    return latlng 
} 

我用這個代碼來生成一個隨機的,但有時,標記不在地圖範圍,

那麼,什麼是錯我的代碼?

感謝

更新:

這是代碼有Math.abs:

http://jsfiddle.net/PNYCf/1/

,這是不是有:

http://jsfiddle.net/pRjBr/

回答

6

你可能想嘗試以下操作:

function getRandom_marker(bounds) { 
    var lat_min = bounds.getSouthWest().lat(), 
     lat_range = bounds.getNorthEast().lat() - lat_min, 
     lng_min = bounds.getSouthWest().lng(), 
     lng_range = bounds.getNorthEast().lng() - lng_min; 

    return new google.maps.LatLng(lat_min + (Math.random() * lat_range), 
           lng_min + (Math.random() * lng_range)); 
} 

完整的示例:

<!DOCTYPE html> 
<html> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
    <title>Google Maps Random Points Demo</title> 
    <script src="http://maps.google.com/maps/api/js?sensor=false" 
      type="text/javascript"></script> 
</head> 
<body> 
    <div id="map" style="width: 400px; height: 300px;"></div> 

    <script type="text/javascript"> 

    function getRandom_marker(bounds) { 
    var lat_min = bounds.getSouthWest().lat(), 
     lat_range = bounds.getNorthEast().lat() - lat_min, 
     lng_min = bounds.getSouthWest().lng(), 
     lng_range = bounds.getNorthEast().lng() - lng_min; 

    return new google.maps.LatLng(lat_min + (Math.random() * lat_range), 
            lng_min + (Math.random() * lng_range)); 
    } 

    var map = new google.maps.Map(document.getElementById('map'), { 
    zoom: 8, 
    center: new google.maps.LatLng(-34.397, 150.644), 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
    }); 

    google.maps.event.addListener(map, 'tilesloaded', function() { 
    var mapBounds = map.getBounds(); 

    for (var i = 0; i < 20; i++) { 
     new google.maps.Marker({ 
     position: getRandom_marker(mapBounds), 
     map: map 
     }); 
    } 
    }); 

    </script> 
</body> 

截圖:

Random Markers

+0

@丹尼爾,我認爲使用數學。 abs是不正確的,因爲lat,lng有負數,看我的更新d。 – zjm1126 2010-09-06 02:29:26

+0

@ zjm1126:你說的對,沒必要,因爲北方總是比南方大,西方比東方大。修復我的答案。 – 2010-09-06 02:38:03

+0

你的第二個代碼不會改變。 Math.abs – zjm1126 2010-09-06 02:53:06