<!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定位服务(REST Services)
            // 需要确保你的API密钥有调用REST服务的权限
            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定位通常返回一个区域(如城市中心)
                        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('定位请求发生错误。');
                });
        }
        function reverseGeocode(location) {
            // 使用Bing Maps的搜索管理器进行反向地理编码,将坐标转换为地址
            if (!searchManager) {
                searchManager = new Microsoft.Maps.Search.SearchManager(map);
            }
            var reverseGeocodeRequestOptions = {
                location: location,
                callback: function (answer, userData) {
                    if (answer && answer.address) {
                        // 在控制台输出格式化地址
                        console.log('反向地理编码结果: ', 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>