【问题标题】:Google map WatchPosition doesn't work properly谷歌地图 WatchPosition 无法正常工作
【发布时间】:2018-01-02 00:20:42
【问题描述】:

我正在尝试实现一个需要跟踪用户位置的功能,首先,我使用 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: "http://i.stack.imgur.com/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: "http://i.stack.imgur.com/orZ4x.png",
        });
        myPosition.setMap(map);
    }else{
        myPosition.setPosition(myLatlng);
    }
    map.panTo(myLatlng);
};

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2016-09-28
      • 2011-03-25
      • 2017-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多