简体   繁体   中英

JS Google Maps API: Avoid grey map if geo location is off

I want to display two markers on my view. The first is static (the "goal") while the second is the current position of the user. If geo location is switched off or there are other reasons why the current location cannot be retrieved, only the first marker should be displayed.

This lead me to the following code:

        var aMarkerPos = [];

        // handle fixed position of goal
        var goalLatlng = new google.maps.LatLng(xx, yy);

        aMarkerPos.push(goalLatlng);

        this.geocoder = new google.maps.Geocoder();
        var mapOptions = {
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        this.map = new google.maps.Map(this.getView().byId("map_canvas").getDomRef(),
            mapOptions);

        var goalMarker = new google.maps.Marker({
            position: goalLatlng,
            map: this.map,
            title: 'GOAL'
        });

        var that = this;

        // Try HTML5 geolocation
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                var currentLatlng = new google.maps.LatLng(position.coords.latitude,
                    position.coords.longitude);

                aMarkerPos.push(currentLatlng);

                var positionMarker = new google.maps.Marker({
                    position: currentLatlng,
                    map: that.map,
                    title: 'My Position'
                });

                // map: an instance of GMap3
                // latlng: an array of instances of GLatLng
                var latlngbounds = new google.maps.LatLngBounds();
                aMarkerPos.forEach(function(n){
                    latlngbounds.extend(n);
                });
                that.map.setCenter(latlngbounds.getCenter());
                that.map.fitBounds(latlngbounds);

            }, function(error) {
                that.map.setCenter(goalLatlng);
            });
        } else {
            this.map.setCenter(goalLatlng);
        }

The code works fine if geo location is active and the current position can be retrieved. In all other cases, the view is just grey. Why??

OMG, this was simple. I just add it so that others might check my fault if they are doing the same: one has to set the center position (and the zoom factor) in the map settings.

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

As soon as I added them, the map did what I wanted...

These are the two required MapOptions :

center  LatLng  The initial Map center. Required.
zoom    number  The initial Map zoom level. Required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM