HTML5地理位置标记移动和地图更新

时间:2011-11-21 22:51:47

标签: html5 geolocation

我正在为学校项目开发基于位置的应用程序,以下脚本每次GPS更新时都会使用新标记绘制地图,留下标记的痕迹。我如何制作它,以便每当GPS更新地图时,地图中心的更新地图标记就会显示(这就像所有移动地图应用程序根据用户的移动标记移动所做的那样)?谢谢。

<!DOCTYPE html>
<html>
<head>
<title>Geolocation default</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1" />
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript">
    var map = null;

    const POSITION_OPTIONS = {enableHighAccuracy:true, maximumAge:30000, timeout:27000};

    function GetMap() {
        map = new Microsoft.Maps.Map(document.getElementById('myMap'), { credentials: 'ArqqdSR0U_ZzTkRh5W_3p0yukEEJ5X0L5QE9rg1CK1uyWgGz1n0Fi_-c2i2IfSN6' });
        GetLocation();
    }

    function GetLocation() {
        //check if location api supported
        if (!!navigator.geolocation) {

            //Update location
            navigator.geolocation.watchPosition(UpdateLocation,HandleErrors,POSITION_OPTIONS);
        }
    }

    function UpdateLocation(position) {
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;

        //move map to new location and zoom in
        map.setView({ center: { latitude: latitude, longitude: longitude }, zoom: 16, mapTypeId: Microsoft.Maps.MapTypeId.aerial });

        var loc = new Microsoft.Maps.Location(latitude, longitude);

        var pin = new Microsoft.Maps.Pushpin(loc); 
        map.entities.push(pin);
    }

    function HandleErrors(error) {
        //handle geolocation errors and alert user
        switch (error.code) {
            case error.PERMISSION_DENIED: alert("user did not share geolocation data");
                break;

            case error.POSITION_UNAVAILABLE: alert("could not detect current position");
                break;

            case error.TIMEOUT: alert("retrieving position timed out");
                break;

            default: alert("unknown error");
                break;
        }  
    }

</script>

</head>
<body onload="GetMap();" style="padding:0;margin:0;">

<div id="myMap" style="position: absolute; width: 100%; height: 100%;">
</div>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

我想说最好的办法是让一些JavaScript代码强制你的页面在给定的时间间隔内重新加载。以下是一些可以帮助您的代码:

var t = setTimeout("window.location.reload(true)",3000);

您可能希望将window.location.reload(true)放入更新函数中,并将update方法传递给setTimeout方法,例如;

var t = setTimeout("UpdateLocation()",3000);

然后,您可能会在将用户坐标传递回服务器之后调用window.location.reload。

希望这有帮助!