【问题标题】:How can I change the location in a map using javascript and google maps?如何使用 javascript 和谷歌地图更改地图中的位置?
【发布时间】:2015-09-11 07:16:15
【问题描述】:

我正在尝试使用 each 循环更改地图的中心以前往不同的地方,但是当我执行代码时,地图不会显示所有位置,而是地图显示第一个和最后一个位置,我将如果你能帮我解决这个问题,感激不尽。

这是代码:

    var a = new google.maps.LatLng(8.8013, -74.72538);
    var b = new google.maps.LatLng(1.0619, -73.2558);
    var c = new google.maps.LatLng(12.5872, -81.7025);
    var d = new google.maps.LatLng(3.2719, -73.0877);

    var locations = new Array(a, b, c, d);
    var mapProp = {
        center: new google.maps.LatLng(5.0619, -70.2558),
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);

    function initialize() {
        goToLocations(locations);
    }
    google.maps.event.addDomListener(window, 'load', initialize);   

    function goToLocations(locations) {
        $.each(locations, function (index, location) {
            goToLocation(location);
        });
    }

    function goToLocation(location) {
      // here I can not see all locations 
        window.setTimeout(map.setCenter(location), 5000);        
    }
<html>  

  <body>
    
    <script src="http://maps.google.com/maps/api/js?sensor=true" type="text/javascript">       </script>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    
    <h1>Map that go to different locations </h1>
    <div id="googleMap" style="width: 500px; height: 380px"></div>
    
  </body>
  
</html>

【问题讨论】:

    标签: javascript google-maps google-maps-api-3 google-maps-markers google-maps-api-2


    【解决方案1】:

    您的function 工作正常,它实际上显示了您在array 上拥有的所有城市。但是,我们无法看到它。 function 执行速度如此之快,以至于我们只能看到第一个和最后一个。

    尝试将Timeout 放入$.each 函数中,它会起作用:

    $.each(locations, function (index, location) {
       window.setTimeout(function(){  
          goToLocation(location);
       }, 1000);
    });
    

    【讨论】:

    • 谢谢,但我尝试在$.each 中添加timeout,但问题仍然存在
    猜你喜欢
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 2021-10-15
    • 2014-06-24
    • 2019-10-24
    • 1970-01-01
    相关资源
    最近更新 更多