如何使用javascript和谷歌地图更改地图中的位置

How can I change the location in a map using javascript and google maps?

本文关键字:地图 位置 何使用 javascript 谷歌地图      更新时间:2023-09-26

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

这是代码:

    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>

您的function运行良好,它实际上显示了array上的所有城市。但是,我们看不到它。function执行得太快了,我们只能看到第一个和最后一个。

尝试在$.each函数中放入一个Timeout,它就会工作:

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