Javascript 如何在我的当前位置html5上居中放置地图
好吧,我敢肯定这是因为我在晚上做的事情太晚了,错过了一些非常简单的事情,所以如果这是我在研究中错过的事情,我真的很抱歉,但是我一直在拖网 我有一个地图,它完美地显示了从一个漂亮的xml文件加载的许多标记(几千个),但是我真的希望地图以客户机当前位置为中心。如果我硬接线,一切都很好,但动态位被证明太难了。我已经在谷歌文档中找到了它,在这里找到了,甚至尝试了反向工程其他一些网站。。。下面是我在body.onload.initialize()上运行的代码 我尝试过使用以下方法:Javascript 如何在我的当前位置html5上居中放置地图,javascript,html,google-maps,google-maps-api-3,Javascript,Html,Google Maps,Google Maps Api 3,好吧,我敢肯定这是因为我在晚上做的事情太晚了,错过了一些非常简单的事情,所以如果这是我在研究中错过的事情,我真的很抱歉,但是我一直在拖网 我有一个地图,它完美地显示了从一个漂亮的xml文件加载的许多标记(几千个),但是我真的希望地图以客户机当前位置为中心。如果我硬接线,一切都很好,但动态位被证明太难了。我已经在谷歌文档中找到了它,在这里找到了,甚至尝试了反向工程其他一些网站。。。下面是我在body.onload.initialize()上运行的代码 我尝试过使用以下方法: var myLat =
var myLat = position.coords.latitude;
var myLng = position.coords.longitude;
然而,这些看起来不像是在这个上下文中公开的
以下是我的声明:
<body onload="initialize()" onunload="GUnload()">
<section id="content" style="width:70%; height:80%">
<div id="map_canvas" style="width:100%; height:80%"></div>
</section>
</body>
我真的不想使用其他第三方库,而是尽可能地坚持使用Google代码的原生版本
感激地接受了任何帮助,这意味着我可以睡得更好:-\使用map resize触发器
// Set the center of the map
map.setCenter(new google.maps.LatLng(lat, lng)); // google.maps.LatLng object!
// Trigger resize event, telling the API to refresh the view
google.maps.event.trigger(map, 'resize');
见类似问题:
API链接:
首先,您需要通过浏览器获得用户的位置权限在获得客户端坐标后,您可以这样做
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(latitude, longitude),
map: map,
title: "Last Location",
icon: "http://i.imgur.com/S1ooXKy.png"
});
map.setCenter(new google.maps.LatLng(latitude, longitude));
map.setZoom(13);
};
function error() {
console.log("Unable to retrieve your location");
};
console.log("Locating…");
navigator.geolocation.getCurrentPosition(success, error);
我看了这两个选项,来自@Notável的一个非常有用@来自德国的丹也很有趣,我会在以后的一段时间里记住这一点
myLat
和myLng
变量声明为全局变量(在此上下文之外)position.coords.
移动到success()
函数中success()
new google.maps.LatLng(纬度、经度)
这很好地达到了预期的效果。感谢所有阅读此问题的人:-)您好@Notável,这帮了大忙,实际上我对它做了一些修改,以便进一步重用。我在函数外部声明了
latitude
和longitude
,以便更容易地传递值,并且创建了一个位置变量var myPOS=new google.maps.LatLng(latitude,longitude)
,然后在地图选项中重用了myPOS。
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(latitude, longitude),
map: map,
title: "Last Location",
icon: "http://i.imgur.com/S1ooXKy.png"
});
map.setCenter(new google.maps.LatLng(latitude, longitude));
map.setZoom(13);
};
function error() {
console.log("Unable to retrieve your location");
};
console.log("Locating…");
navigator.geolocation.getCurrentPosition(success, error);