Javascript 谷歌地图 setCenter()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2773263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Google Maps setCenter()
提问by hotcoder
I'm using google maps. In my code i've used setCenter() function. My problem is that marker is always located on top left corner of map area (not at the center). Please tell me how to resolve it?
我正在使用谷歌地图。在我的代码中,我使用了 setCenter() 函数。我的问题是标记始终位于地图区域的左上角(而不是中心)。请告诉我如何解决它?
My piece of code is
我的一段代码是
lat = 46.437857;
lon = -113.466797;
marker = new GMarker(new GLatLng(lat, lon));
var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(20, 40));
map.addControl(new GLargeMapControl3D(), topRight);
map.setCenter(new GLatLng(lat, lon), 5);
map.addOverlay(marker);
采纳答案by hotcoder
function resize() {
var map_obj = document.getElementById("map_canvas");
/* map_obj.style.width = "500px";
map_obj.style.height = "225px";*/
if (map) {
map.checkResize();
map.panTo(new GLatLng(lat,lon));
}
}
<body onload="initialize()" onunload="GUnload()" onresize="resize()">
<div id="map_canvas" style="width: 100%; height: 100%">
</div>
回答by Hammad Khan
@phoenix24 answer actually helped me (whose own asnwer did not solve my problem btw). The correct arguments for setCenter is
@phoenix24 答案实际上帮助了我(顺便说一句,他自己的问题并没有解决我的问题)。setCenter 的正确参数是
map.setCenter({lat:LAT_VALUE, lng:LONG_VALUE});
By the way if your variable are lat and lng the following code will work
顺便说一句,如果您的变量是 lat 和 lng,则以下代码将起作用
map.setCenter({lat:lat, lng:lng});
This actually solved my very intricate problem so I thought I will post it here.
这实际上解决了我非常复杂的问题,所以我想我会把它贴在这里。
回答by user459913
I searched and searched and finally found that ie needs to know the map size. Set the map size to match the div size.
搜了又搜,终于发现ie需要知道地图大小。设置地图大小以匹配 div 大小。
map = new GMap2(document.getElementById("map_canvas2"), { size: new GSize(850, 600) });
<div id="map_canvas2" style="width: 850px; height: 600px">
</div>
回答by itzmukeshy7
For me above solutions didn't work then I tried
对我来说,上述解决方案不起作用,然后我尝试了
map.setCenter(new google.maps.LatLng(lat, lng));
and it worked as expected.
它按预期工作。
回答by phoenix24
in your code, at line
在您的代码中,在行
map.setCenter(new GLatLng(lat, lon), 5);
the setCenter method takes just one parameter, for the lat:long location. Why are you passing two parameters there ?
setCenter 方法只需要一个参数,用于 lat:long 位置。为什么要在那里传递两个参数?
I suggest you should change it to,
我建议你应该改成,
map.setCenter(new GLatLng(lat, lon));

