<!DOCTYPE html>
<html>
<head>
<title>Bing Maps 地理位置獲取</title>
<meta charset="utf-8">
<script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?key=YOUR_BING_MAPS_API_KEY&callback=loadMapScenario' async defer></script>
<script type='text/javascript'>
var map, searchManager;
function loadMapScenario() {
map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
/* 可選:初始地圖中心點和縮放級別 */
// center: new Microsoft.Maps.Location(39.916527, 116.397128),
// zoom: 10
});
// 嘗試獲取用戶精確位置
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
// 瀏覽器定位成功
var userLocation = new Microsoft.Maps.Location(
position.coords.latitude,
position.coords.longitude
);
displayUserLocation(userLocation, "瀏覽器精確定位");
},
function (error) {
// 瀏覽器定位失?。ㄓ脩艟芙^或超時等),回退到IP定位
console.error('瀏覽器定位失敗: ', error);
alert('精確定位失敗,將嘗試獲取大致城市位置。');
getLocationByIP();
},
{
// 定位選項
enableHighAccuracy: true, // 請求高精度
timeout: 10000, // 超時時間(10秒)
maximumAge: 600000 // 緩存位置的最大年齡(10分鐘)
}
);
} else {
// 瀏覽器不支持Geolocation API
alert('您的瀏覽器不支持地理位置功能。');
getLocationByIP();
}
}
function displayUserLocation(location, source) {
// 將地圖中心移動到用戶位置
map.setView({ center: location, zoom: 15 });
// 添加一個圖釘
var pin = new Microsoft.Maps.Pushpin(location, {
title: '您的位置 (' + source + ')',
text: '??'
});
map.entities.push(pin);
// 可選:進行反向地理編碼獲取地址信息
reverseGeocode(location);
}
function getLocationByIP() {
// 使用Bing Maps的IP定位服務(wù)(REST Services)
// 需要確保你的API密鑰有調(diào)用REST服務(wù)的權(quán)限
var apiKey = "YOUR_BING_MAPS_API_KEY"; // 替換你的密鑰
var ipLocUrl = `https://dev.virtualearth.net/REST/v1/Locations?key=${apiKey}`;
fetch(ipLocUrl)
.then(response => response.json())
.then(data => {
if (data.resourceSets && data.resourceSets.length > 0 && data.resourceSets[0].resources.length > 0) {
// IP定位通常返回一個區(qū)域(如城市中心)
var coords = data.resourceSets[0].resources[0].point.coordinates;
var ipLocation = new Microsoft.Maps.Location(coords[0], coords[1]);
displayUserLocation(ipLocation, "IP定位");
} else {
alert('無法通過IP確定位置。');
}
})
.catch(error => {
console.error('IP定位請求失敗: ', error);
alert('定位請求發(fā)生錯誤。');
});
}
function reverseGeocode(location) {
// 使用Bing Maps的搜索管理器進行反向地理編碼,將坐標轉(zhuǎn)換為地址
if (!searchManager) {
searchManager = new Microsoft.Maps.Search.SearchManager(map);
}
var reverseGeocodeRequestOptions = {
location: location,
callback: function (answer, userData) {
if (answer && answer.address) {
// 在控制臺輸出格式化地址
console.log('反向地理編碼結(jié)果: ', answer.address.formattedAddress);
// 你也可以將地址顯示在圖釘或頁面的其他部分
}
},
errorCallback: function (e) {
console.log("反向地理編碼失敗");
}
};
searchManager.reverseGeocode(reverseGeocodeRequestOptions);
}
</script>
</head>
<body>
<div id='myMap' style='width: 100vw; height: 100vh;'></div>
</body>
</html>