昨天老板告诉我代码有Bug(定位失败),于是各种测试最终发现IOS10以上版本手机不能成功,先贴失败代码:
var city =""; navigator.geolocation.getCurrentPosition(function(position) { var lat = position.coords.latitude; var lon = position.coords.longitude; var point = new BMap.Point(lon, lat); // 创建坐标点 // 根据坐标得到地址描述 var myGeo = new BMap.Geocoder(); myGeo.getLocation(point, function(result) { city= result.addressComponents.city; alert(city); }); });
经过查阅资料得知IOS系统在10以上版本考虑到安全问题禁止用户在http协议下定位,要想定位必须将http协议升级成https协议,当然也有别的办法,比如调用百度地图API接口实现,废话不多,上代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=你的Key(在百度地图免费申请)"></script> <title>定位</title> </head> <body> <div id="allmap" style="width: 0;height: 0; display: none;"></div> <script type="text/javascript"> // 百度地图API功能 var map = new BMap.Map("allmap"); var point = new BMap.Point(108.95,34.27); map.centerAndZoom(point,12); var geolocation = new BMap.Geolocation(); geolocation.getCurrentPosition(function(r){console.log(r.point) if(this.getStatus() == BMAP_STATUS_SUCCESS){ var mk = new BMap.Marker(r.point); map.addOverlay(mk); map.panTo(r.point); var point = new BMap.Point(r.point.lng,r.point.lat); var gc = new BMap.Geocoder(); gc.getLocation(point, function(rs){ var addComp = rs.addressComponents; console.log(rs); alert(addComp.city+"==="+addComp.district) }); }else { alert(‘failed‘+this.getStatus()); } },{enableHighAccuracy: true}) </script> </body>
利用百度地图API接口完美解决。
时间: 2024-10-03 23:54:02