简体   繁体   English

谷歌地图-变更中心

[英]google map - change centers

this code will move map center to one of four locations. 此代码会将地图中心移动到四个位置之一。 It works but seems slow. 它有效,但似乎很慢。 Is it possible to get better performance by caching 4 maps in advance or something like that? 是否可以通过预先缓存4张地图或类似的东西来获得更好的性能? Maybe running the initialize function each time is slowing us down? 也许每次都运行初始化函数会使我们减速吗?

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script src="../jquery/jquery.js" type="text/javascript"></script>  

    <script>


$( document ).ready(function() {

    var map;
    var montreal = new google.maps.LatLng(45.504 , -73.597);
    var newCenter = montreal
    var toronto = new google.maps.LatLng(43.65304 , -79.32129);
    var calgary = new google.maps.LatLng(50.99394, -114.16992);
    var vancouver = new google.maps.LatLng(49.18984, -123.17871);

    function initialize() {
      var mapDiv = document.getElementById('map-canvas');
      var mapOptions = {
        zoom: 10,
        center: newCenter
      }
      map = new google.maps.Map(mapDiv, mapOptions);
    }

    google.maps.event.addDomListener(window, 'load', initialize);

    $( "#location_1" ).on( "click", function() {
      newCenter = montreal;
      initialize();
    });

    $( "#location_2" ).on( "click", function() {
        newCenter = toronto;
        initialize();
    });
    $( "#location_3" ).on( "click", function() {
        newCenter = calgary;
        initialize();
    });
    $( "#location_4" ).on( "click", function() {
        newCenter = vancouver;
        initialize();
    });

});

  </script>
  </head>
  <body>
  <button id='location_1'>Montreal</button>
  <button id='location_2'>Toronto</button>
  <button id='location_3'>Calgary</button>
  <button id='location_4'>Vancouver</button>

    <div id="map-canvas"></div>

you can try using setCenter() to change the center of the map without the need to call the initialize function again, here's how 您可以尝试使用setCenter()更改地图中心,而无需再次调用initialize函数,这是

$( "#location_1" ).on( "click", function() {
  map.setCenter(montreal);
});

$( "#location_2" ).on( "click", function() {
    map.setCenter(toronto);
});
$( "#location_3" ).on( "click", function() {
    map.setCenter(calgary);
});
$( "#location_4" ).on( "click", function() {
    map.setCenter(vancouver);
});

Use map.setCenter() . 使用map.setCenter() calling the initialize() function would slow down since you are creating another instance of the map object. 由于您正在创建地图对象的另一个实例,因此调用initialize()函数会减慢速度。

Reference: https://developers.google.com/maps/documentation/javascript/reference 参考: https : //developers.google.com/maps/documentation/javascript/reference

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM