HTML5获取地理位置信息并在Google Maps上显示

时间:2023-12-13 13:32:32
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{margin:0; padding:0;}
.kingwell_test{font-size:12px; color:#333}
#ms{height:30px; line-height:30px; font-size:1.25em}
#map{width:400px; height:400px; margin:auto}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function $(id) {
return document.getElementById(id);
}
function showInfo(mes){
$('ms').innerHTML = mes;
setTimeout(function (){
$('ms').innerHTML = '';
},2000);
};
function getPosition(){
if(!navigator.geolocation){
//alert('不支持定位');
return;
}
navigator.geolocation.getCurrentPosition(function(position){
var coords = position.coords;
$('latitude').innerHTML = coords.latitude;
$('longitude').innerHTML = coords.longitude;
$('accuracy').innerHTML = coords.accuracy;
//设定地图参数
var latlng = new google.maps.LatLng(coords.latitude,coords.longitude);
var myOptions = {
zoom:14,
center:latlng,
mapTypeId : google.maps.MapTypeId.ROADMAP
}
var map1 = new google.maps.Map($('map'),myOptions);
var marker = new google.maps.Marker({
position:latlng,
map :map1
});
var infowindow = new google.maps.InfoWindow({
content : '您当前位置'
});
infowindow.open(map1,marker);
},function(er){
var errorType = {
1 : '位置服务被拒绝',
2 : '获取不到位置信息',
3 : '获取信息超时'
};
showInfo(errorType[er.code]);
},{
enableHighAccuracy :false,
//maximumAge : 60*1000/2,
//timeout : 5000
});
}
window.addEventListener('load',function(){
getPosition();
}); </script>
</head>
<body>
<div id="map"></div>
<div class="kingwell_test">
<div id="ms"></div>
<div id="">经度:<span id="latitude"></span></div>
<div id="">纬度:<span id="longitude"></span></div>
<div id="">精确度:<span id="accuracy"></span></div>
</div>
</body>
</html>

经度:
纬度:
精确度: