【问题标题】:Random marker within a rectangular bounds?矩形范围内的随机标记?
【发布时间】:2010-09-06 01:49:57
【问题描述】:

这是我的代码:

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/

【问题讨论】:

    标签: javascript google-maps random


    【解决方案1】:

    您可能想尝试以下方法:

    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> 
    

    截图:

    【讨论】:

    • @Daniel,我认为使用 Math.abs 是不对的,因为 lat,lng 有负数,看我更新了。
    • @zjm1126:你说得对,没必要,因为北总是比南大,西比东大。修正我的答案。
    猜你喜欢
    • 2011-12-16
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多