2014-09-03 68 views
0

此代碼將地圖中心移動到四個位置之一。它有效,但似乎很慢。提前緩存4張地圖或類似的東西是否有可能獲得更好的性能?也許每次運行初始化函數都會讓我們放慢速度?谷歌地圖 - 更改中心

<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> 
+0

我認爲'initialize'方法是緩慢的,因爲你重繪基於更新的'地圖mapOptions'」 – 2014-09-03 02:23:45

回答

1

你可以嘗試使用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); 
});