地理定位标记靠近视口边缘时接收地图

时间:2015-11-27 21:49:26

标签: google-maps google-maps-api-3

我正在为一个当地的土地保护项目开展一个小型志愿者项目,该项目显示了他们维护的小径的KML地图数据,并显示了人们在路上徒步旅行的标记。

当标记靠近视口边缘时,我需要地图重新定位。

找不到示例代码。

以下是我目前用于地图绘制的内容:

<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<script src="//google-maps-utility-library-v3.googlecode.com/svn/trunk/geolocationmarker/src/geolocationmarker-compiled.js"></script>
<script>
  var map, GeoMarker;
  var ojai = new google.maps.LatLng(34.4487119,-119.247359);

  function initialize() {
    var mapOptions = {
      zoom: 12,
      center: ojai,
      mapTypeId: google.maps.MapTypeId.SATELLITE
    };
    map = new google.maps.Map(document.getElementById('map_canvas'),
        mapOptions);


         /* Trail KML Data Layer
         ------------------------------------------------- */
         var trailLayer = new google.maps.KmlLayer({
            url: 'http://example.com/trail.kml', 
            preserveViewport: true // don't resize viewport to fit KML data
            });

          ovlcLayer.setMap(map);



    GeoMarker = new GeolocationMarker();
    GeoMarker.setCircleOptions({fillColor: '#808080'});

    google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function() {
      map.setCenter(this.getPosition());
      //map.panTo(this.getPosition());
      map.fitBounds(this.getBounds());
    });

    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');
  }  

     </script>

1 个答案:

答案 0 :(得分:2)

更新地理位置时,检查地理位置是否在地图边界内,如果地图不是,则重新定位地图。

google.maps.event.addListener(GeoMarker, 'position_changed', function() {
  if (!map.getBounds().contains(GeoMarker.getPosition()))
  map.setCenter(this.getPosition());
});