Google Maps API:在不重新加载地图的情况下关注和居中我的监视位置

时间:2014-02-08 11:18:32

标签: javascript html5 google-maps-api-3 geolocation

几个月以来,我一直在寻找解决方案。我发现了一些非常有趣的东西 - 比如Google Maps Library Utilities,但没有什么可以帮助我。

我想通过使用watchPosition和跟随(居中)我的位置来获取我在谷歌地图上的位置,而无需重新加载地图。

每次我将该位置置于watchPosition的中心位置时,它会重新加载地图。也许有一种覆盖的方法,但不幸的是,我缺乏知识。

最好的方法是使用Google Maps Library Utilities中的Geomarker。但这里也一样。我无法集中精力。

也许有人可以用一个有效的例子来帮助我。

2 个答案:

答案 0 :(得分:1)

var map;
            var GeoMarker;
            function initialize() {
                var mapOptions = {
                    zoom: 12,
                    center: new google.maps.LatLng(-34.397, 150.644),
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

                GeoMarker = new GeolocationMarker();
                GeoMarker.setCircleOptions({fillColor: '#808080'});
                google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function() {
                    map.setCenter(this.getPosition());
                    map.fitBounds(this.getBounds());
                });

                navigator.geolocation.watchPosition(function(position) {
                    var latitude = position.coords.latitude;
                    var longitude = position.coords.longitude;
                    var geolocpoint = new google.maps.LatLng(latitude, longitude);
                    map.setCenter(geolocpoint);
                });

                google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) {
                    alert('There was an error obtaining your position. Message: ' + e.message);
                });
                GeoMarker.setMap(map);
            }

            google.maps.event.addDomListener(window, 'load', initialize);
            if(!navigator.geolocation) {
                alert('Your browser does not support geolocation');
            }

答案 1 :(得分:0)

您无需重新加载地图。

使用标记的setPosition - 方法应用新位置(如果可用),并使用地图的setCenter - 方法应用新中心。