2010-09-06 3 views
1

ceci est mon code:Marqueur aléatoire dans une limite rectangulaire?

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 
} 

i utiliser ce code pour générer un hasard, mais parfois, le marqueur est pas dans les limites de carte,

donc, quel est le problème avec mon code?

grâce

mise à jour:

c'est le code a Math.abs:

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

et cela ne doit:

http://jsfiddle.net/pRjBr/

Répondre

6

Vous pouvez essayer ce qui suit:

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)); 
} 

Exemple complet:

<!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> 

Screenshot:

Random Markers

+0

@ Daniel, je pense utiliser le Math. abs n'est pas juste, parce que lat, lng a un nombre négatif, regardez ma mise à jour ré. – zjm1126

+0

@ zjm1126: Vous avez raison, ce n'est pas nécessaire, car North sera toujours plus grand que South, et West plus grand que East. Fixer ma réponse. –

+0

votre deuxième code n'a pas changé. a également Math.abs – zjm1126

Questions connexes