getCurrentPosition未调用

亨里克

我正在尝试在地图上将用户当前位置居中。

但是我很难弄清楚为什么getCurrentPosition只是被跳过了。当我调试它时,请跳过该行。

我究竟做错了什么?

initMap: function() {
    var latLng;

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            function(position) {
                latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
            }, function() {
                latLng = new google.maps.LatLng(37.4, -122.1)
            }, {
                timeout: 10000
            }
        );
    };

    var mapOptions = {
        center: latLng,
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    this.oMap = new google.maps.Map(this.getView().byId("map_canvas").getDomRef(), mapOptions);
    this.geocoder = new google.maps.Geocoder();
    this.directionsService = new google.maps.DirectionsService();
    this.directionsDisplay = new google.maps.DirectionsRenderer({
        draggable: true,
        map: this.oMap,
        suppressMarkers: true
    });

    this.createCurrentLocationMarker();
    this.loadDataFromModel();
}
用户405398

由于评论中提到的F​​rédéricHamidinavigator.geolocation可能在您正在测试的浏览器中不可用。

但是还需要做更多的事情。latlang在它填充之前,您无法访问因此,即使您在具有的浏览器中进行测试,也必须将代码更改为如下所示navigator.geolocation

initMap: function() {
    var latLng;

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            function(position) {
                latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                var mapOptions = {
                      center: latLng,
                      zoom: 12,
                      mapTypeId: google.maps.MapTypeId.ROADMAP
                };

                this.oMap = new google.maps.Map(this.getView().byId("map_canvas").getDomRef(), mapOptions);
                this.geocoder = new google.maps.Geocoder();
                this.directionsService = new google.maps.DirectionsService();
                this.directionsDisplay = new google.maps.DirectionsRenderer({
                     draggable: true,
                     map: this.oMap,
                     suppressMarkers: true
                 });

                 this.createCurrentLocationMarker();
                 this.loadDataFromModel();
            }.bind(this), function() {
                latLng = new google.maps.LatLng(37.4, -122.1)
            }, {
                timeout: 10000
            }
        );
    }; 
}

现在,您的代码将在运行之后latlang可用,并且还要注意.bind(this)确保this回调中的代码相同。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章