设置GPS和标记之间的地图边界

Setting map bounds between GPS and marker

本文关键字:地图 边界 之间 GPS 设置      更新时间:2023-09-26

我不明白如何设置地图边界。我看了其他几个相关的问题,但我不能让它们正常工作。

这就是我正在尝试的:http://jsfiddle.net/ZFyDY/

在每个标记之后,我调整地图的边界,如下所示:

var bounds = new google.maps.LatLngBounds();
bounds.extend(gps_coords);

我做错了什么?

不要每次(为每个标记)都创建一个新的空边界对象,在开始时创建一个,将所有的点添加到它,然后使用它来缩放和居中地图。

代码片段:

function map_init() {
  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  var bounds = new google.maps.LatLngBounds();
  // Add GPS location
  /*
  var sensor_image = new google.maps.MarkerImage("#{asset_path "
    sensor.png "}",
    new google.maps.Size(38, 38),
    new google.maps.Point(0, 0),
    new google.maps.Point(19, 19));
    */
  if (navigator.geolocation) {
    browserSupportFlag = true;
    navigator.geolocation.getCurrentPosition(function(position) {
      var gps_coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
      new google.maps.Marker({
        position: gps_coords,
        map: map,
        // icon: sensor_image
      });
      var bounds = new google.maps.LatLngBounds();
      bounds.extend(gps_coords);
    }, function() {
      // Handle no geolocation support
    })
  }
  //Add Store location
  geocoder = new google.maps.Geocoder();
  geocoder.geocode({
    'address': "New York, NY"
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      var store_coords = results[0].geometry.location;
      new google.maps.Marker({
        position: store_coords,
        animation: google.maps.Animation.DROP,
        map: map
      });
      bounds.extend(store_coords);
      map.fitBounds(bounds);
    }
  });
  geocoder.geocode({
    'address': "Boston, MA"
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      var store_coords = results[0].geometry.location;
      new google.maps.Marker({
        position: store_coords,
        animation: google.maps.Animation.DROP,
        map: map
      });
      bounds.extend(store_coords);
      map.fitBounds(bounds);
    }
  });
  //Configure map
  //bounds.extend(gps_coords);
  //bounds.extend(store_coords);
  map.fitBounds(bounds);
}
google.maps.event.addDomListener(window,'load', map_init)
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>