如何将Google地图定位到特定位置?

时间:2014-06-05 05:02:04

标签: javascript css google-maps

我在三个不同的div上有三张地图画布。在javascript中,我将中心设置为三个中的相同位置。但第二个和第三个没有得到那个中心。可能是什么问题呢? 有什么想法吗?

var centerPosition=new google.maps.LatLng(6.924782, 79.863643);
function initialize() {
    var map_canvas1 = document.getElementById('map_canvas1');
    var map_canvas2 = document.getElementById('map_canvas2');
    var map_canvas3 = document.getElementById('map_canvas3');
    var map_options1 = {
      center: centerPosition,
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

var map_options2 = {
  center: centerPosition,
  zoom: 8,
  mapTypeId: google.maps.MapTypeId.ROADMAP
};

var map_options3 = {
  center: centerPosition,
  zoom: 8,
  mapTypeId: google.maps.MapTypeId.ROADMAP
};
map1 = new google.maps.Map(map_canvas1, map_options1);
map2 = new google.maps.Map(map_canvas2, map_options2);
map3 = new google.maps.Map(map_canvas3, map_options3);

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

2 个答案:

答案 0 :(得分:2)

Please refer to the jsfiddle. Your code is working fine
http://jsfiddle.net/2mw6b/
var centerPosition=new google.maps.LatLng(6.924782, 79.863643);
function initialize() {
    var map_canvas1 = document.getElementById('map_canvas1');
    var map_canvas2 = document.getElementById('map_canvas2');
    var map_canvas3 = document.getElementById('map_canvas3');
    var map_options1 = {
      center: centerPosition,
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

var map_options2 = {
  center: centerPosition,
  zoom: 8,
  mapTypeId: google.maps.MapTypeId.ROADMAP
};

var map_options3 = {
  center: centerPosition,
  zoom: 8,
  mapTypeId: google.maps.MapTypeId.ROADMAP
};
map1 = new google.maps.Map(map_canvas1, map_options1);
map2 = new google.maps.Map(map_canvas2, map_options2);
map3 = new google.maps.Map(map_canvas3, map_options3);

}
initialize();

**Html code**
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v3&libraries=places,drawing&sensor=false"></script>
<div id="map_canvas1" class="mapCont"></div>
<div id="map_canvas2" class="mapCont"></div>
<div id="map_canvas3" class="mapCont"></div>
**Css**
.mapCont{
    height: 200px;
    width: 200px;
}

答案 1 :(得分:1)

而不是使用&#39; center&#39;在JSON对象中的属性,您还可以设置每个地图的中心位置。

请在实例化地图对象后尝试以下代码

 map1.setCenter(centerPosition);
 map2.setCenter(centerPosition);
 map3.setCenter(centerPosition);