javascript - Google map WatchPosition 无法正常工作

标签 javascript angularjs google-maps ionic-framework google-maps-markers

我正在尝试实现一个需要跟踪用户位置的功能,首先,我使用 getCurrentLocation 检索用户的位置,然后传递坐标以放置指示用户位置的标记(标记变量是全局设置的),然后我调用 watchPosition 函数,以便它可以跟踪用户位置(如果其位置已更改)。 此代码是为 Ionic 应用程序实现的,但相同的逻辑将用于任何 Web 应用程序(您可以忽略 $cordovaGeolocation,因为它与 navigator.geolocation 相同)

var map = null;
var myPosition = null;

$scope.initMap = function(){
    var posOptions = {
        enableHighAccuracy: false,
        timeout: 20000,         
    };

    $cordovaGeolocation.getCurrentPosition(posOptions).then(
        function (position) {
            var lat  = position.coords.latitude;
            var long = position.coords.longitude;
            var myLatlng = new google.maps.LatLng(lat, long);               
            $scope.me = myLatlng;

            var mapOptions = {
                center: myLatlng,
                zoom: 11,
                disableDefaultUI: true,
                mapTypeId: google.maps.MapTypeId.ROADMAP,

            };          

            map = new google.maps.Map(document.getElementById("map"), mapOptions); 

            myPosition = new google.maps.Marker({
                map: map,
                position: myLatlng,
                draggable:false,
                icon: "/image/orZ4x.png",
            });             
            var circle = new google.maps.Circle({radius: User.getUser().distance*1000, center: myLatlng}); 
            map.fitBounds(circle.getBounds());              
            $cordovaGeolocation.watchPosition(win);
        },
        function(err) {
            console.log(err);
        }
    );
}

watchPosition 函数的回调如下:

var win = function(position) {
    var lat = position.coords.latitude;
    var long = position.coords.longitude;
    var myLatlng = new google.maps.LatLng(lat, long);
    if(myPosition==null){
        myPosition = new google.maps.Marker({
            map: map,
            position: myLatlng,
            draggable:false,
            icon: "/image/orZ4x.png",
        });
        myPosition.setMap(map);
    }else{
        myPosition.setPosition(myLatlng);
    }
    map.panTo(myLatlng);
};

最佳答案

基本上,这里的错误是 $cordovaGeolocation 的问题,将其替换为 navigator.geolocation 解决了我的问题。

关于javascript - Google map WatchPosition 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45330987/

相关文章:

java - 如何在 Android 版 Google map 上显示路线

javascript - 世博会去 Stripe : Native module cannot be null

javascript - 如何在 highchart 工具提示中显示前 100 个字符,然后说 "See more .."?

使用 ng-messages 进行 AngularJS 选择框验证

javascript - AngularJS: "TypeError: undefined is not a function"与 routeProvider

iphone - 通过在 iPhone 中进行动态图钉注释从 Google map 中选择位置

javascript - 如何使用 Javascript 在 Google Map v3 中使用 GTFS feed?

javascript - 我如何将这个动态 CSS 点图变成折线图?

javascript - 通过跨不同子域的 JavaScript 读取 JSON 文件?

javascript - 带有 $http 请求的 AngularJS 指令(inprog 错误)