Google Maps v3 API扩展边界map.fitBounds无法扩展边界

时间:2012-07-11 00:13:48

标签: javascript google-maps

地图显示2个标记,一个带有地理位置坐标,另一个带有一些随机坐标。我无法扩展边界以适应地图中的两个标记。怎么了?提前谢谢你。

<!DOCTYPE html>
<html>
  <head>
    <title>Google Maps JavaScript API v3 Example: Map Geolocation</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=yes">
    <meta charset="UTF-8">
    <link href="https://google-developers.appspot.com/maps/documentation/javascript/examples/default.css"
      rel="stylesheet" type="text/css">

    <script type="text/javascript"
        src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>

    <script type="text/javascript">
      var map;

      function initialize() {
        var myOptions = {
          zoom: 18,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map_canvas'),
            myOptions);

        // Try HTML5 geolocation
        if(navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
            var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            var geolocation = new google.maps.Marker({position: pos, map: map, title: 'Your geolocation', });

            var latitude=47.03249;
            var longitude=28.833747;
            var pos2=new google.maps.LatLng(latitude,longitude);
            var geolocation2 = new google.maps.Marker({position: pos2,map: map,title: 'Your geolocation',});

            var pos3=new google.maps.LatLng((position.coords.latitude+latitude)/2,(position.coords.longitude+longitude)/2);
            map.setCenter(pos3);

            bounds.extend(geolocation.getPosition());              
            bounds.extend(geolocation2.getPosition());  

    map.fitBounds(bounds);

            }, 
            function() {handleNoGeolocation(true);});
        } 
        else {handleNoGeolocation(false);
        }

      }

      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="map_canvas" style='width:400px; height:400px;'></div>
  </body>
</html>

1 个答案:

答案 0 :(得分:1)

你的界限必须是google.maps.LatLngBounds对象 你永远不构建它。

添加(在你调用extend之前的某个地方):

var bounds = new google.maps.LatLngBounds();

BTW - 你应该得到javascript错误,这使得这一点非常清楚。