首先在页面添加 JS API 的入口脚本标签,并将其中「您申请的key值」替换为您刚刚申请的 key
百度:
<script type="text/javascript" src="//api.map.baidu.com/api?v=2.0&ak=您的密钥"></script>
高德:
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=您申请的key值"></script>
1、百度定位获取
//定位
function getLocation() {
let geolocation = new BMap.Geolocation();
geolocation.enableSDKLocation(); //允许SDK辅助
geolocation.getCurrentPosition(function (r) {
if (this.getStatus() == 0) {
getStreet(r.longitude, r.latitude);
}
});
}
//用所定位的经纬度查找所在地省市街道等信息
function getStreet(longitude, latitude) {
var point = new BMap.Point(longitude, latitude);
var gc = new BMap.Geocoder();
gc.getLocation(point, function (rs) {
console.log(rs);
});
}
2、高德定位获取
//定位
function getLocation() {
let map = new AMap.Map('container');
map.plugin("AMap.Geolocation", function () {
let geolocation = new AMap.Geolocation({
enableHighAccuracy: true, // 是否使用高精度定位,默认:true
convert: true,
showMarker: true,
panToLocation: true,
timeout: 10000,
});
geolocation.getCurrentPosition();
// map.addControl(geolocation);
AMap.event.addListener(geolocation, "complete", onComplete);
AMap.event.addListener(geolocation, "error", onError);
function onComplete(data) {
const {formattedAddress,position} = data;
}
function onError(data) {
// 定位出错
window.alert("定位出错!");
}
});
}