HTML5 Geolocation定位来得如此简单

本文提供两个HTML5地理定位功能示例,一是获取并显示访问者的经纬度坐标,二是结合Google Maps API显示用户当前位置的地图标记。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

示例一 取访问者的经纬度:

<!DOCTYPE html>  
<html>  
<head>  
<meta charset="utf-8">  
<title>HTML5 Geolocation</title>  
<style>  
body {background-color:#fff;}  
</style>  
</head>  
<body>  

<p id="geo_loc"><p>

<script>    
  function getElem(id) {  
       return typeof id === 'string' ? document.getElementById(id) : id;  
   }  
       
    function show_it(lat, lon) {  
        var str = '您当前的位置,纬度:' + lat + ',经度:' + lon;  
       getElem('geo_loc').innerHTML = str;  
    }  
      
   if (navigator.geolocation) {  
       navigator.geolocation.getCurrentPosition(function(position) {    
           show_it(position.coords.latitude, position.coords.longitude);    
       }, function(err) {  
           getElem('geo_loc').innerHTML = err.code + "\n" + err.message;  
       });  
   } else {  
       getElem('geo_loc').innerHTML = "您当前使用的浏览器不支持Geolocation服务";  
   }  
</script>   
</body>  
</html>  
 


 

示例二 与google map 结合怎么样?

 

<!DOCTYPE html>  
<html>  
<head>  
<meta charset="utf-8">  
<title>HTML5 Geolocation</title>  
<style>  
body {background-color:#fff;}  
</style>  
</head>  
<body>  

<p id="map_canvas"><p>

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>  
<script>  
function getElem(id) {  
    return typeof id === 'string' ? document.getElementById(id) : id;  
}  
  
function success(position) {  
    var mapcanvas = document.createElement('div');  
    mapcanvas.id = 'mapcanvas';  
    mapcanvas.style.height = '400px';  
    mapcanvas.style.width = '560px';  
  
    getElem("map_canvas").appendChild(mapcanvas);  
  
    var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);   
    var myOptions = {  
        zoom: 15,  
        center: latlng,  
        mapTypeControl: false,  
        navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},  
        mapTypeId: google.maps.MapTypeId.ROADMAP  
    };  
    var map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);  
    var marker = new google.maps.Marker({  
      position: latlng,   
      map: map,   
      title:"你在这里!"  
    });  
}  
   
if (navigator.geolocation) {  
   navigator.geolocation.getCurrentPosition(success);   
} else {  
  alert("您当前使用的浏览器不支持geolocation服务");  
}    
</script>  
  
</body>  
</html>  
 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值