[英]Get the current LatLng dynamically (Google Map)
我下面有以下代码:
<!DOCTYPE html>
<head>
<title>Geolocation Service</title>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
var lat = ???;
var lng = ???;
var map = {
center:new google.maps.LatLng(lat,lng),
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("mapcontainer"), map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="mapcontainer">
<!--Map goes here-->
</div>
</body>
<style>
*
{
margin: 0;
}
#mapcontainer
{
width: 100vw;
height: 100vh;
}
</style>
</html>
在我的变量lat
和lng
,将它们设置为???
因为我不知道如何获得当前职位。 我刚刚开始学习Google Geolocation API。 谢谢!
如果您使用Google Loader加载Google Maps,则可以使用google.loader.CurrentLocation
获取基于IP的位置,如本答案所示
另一个选择是利用HTML5 GeoLocation API :
function initialize() {
// Is HTML5 geolocation supported
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
var lat = position.coords.latitude;
var lng = position.coords.longitude;
//..
});
}
}
您可能会发现Google Maps JavaScript API-地理位置示例很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.