设置初始中心并放大 google 地图 API

Set initial center and zoom in google maps API

如果我们直接打开google地图,初始视图是我们的城市,城市被放大并适合整个屏幕。

如果我们基于 google 地图 API 创建一个地图网络应用程序(没有设置中心和缩放参数),初始视图是空白的。

问题是:如何使地图 Web 应用程序的行为与 google 地图相同(例如,显示初始地图视图,因为用户的城市适合整个屏幕)?

期待答案,希望代码越少越好。

对于 Bing 地图 API,城市适合视图,无需设置地图的中心和缩放比例。

您提到您希望地图最初设置在用户所在的城市。基于这个用例,我们有必要首先知道我们的用户在哪个城市。一种检测方法是使用 HTML5 的地理位置 API.

我知道您觉得请求许可的弹出窗口很烦人,但请注意,正如 Geolocation API 的文档 (Item 4.1)

中所述

User agents must not send location information to Web sites without the express permission of the user.

这就是要求权限的弹出窗口的原因。

假设您对此没有问题(如果您愿意,您始终可以选择使用其他用户位置检测策略),然后,在获取目标用户的位置后(在地理坐标形式),您可以使用 Geocoding API 对其进行反向地理编码。这将为我们提供与这些坐标匹配的地址列表。

从这个地址列表中,您可以 select 与其所在城市相对应的地址。请注意,对于这部分,您可能需要使用不同的组件集以与不同地区使用的地址格式对齐。

根据此 doc,类型为 locality 的地点表示合并的城市或城镇政治实体。

但是,在某些情况下,例如在英国和瑞典,显示城市的组件是 postal_town。布鲁克林是另一个特例,因为它使用 sublocality_level_1 来表示城市。我在下面的代码示例中考虑了这些特殊情况。

select输入城市地址后,您可以获得它的 locationviewport 并在您要实例化的地图中使用它们。

但请随时根据您的用例修改下面的代码示例:

function initmap() {
// Get location first using HTML5 Geolocation API
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(geocodePosition);
  } else {
    alert("Geolocation is not supported by this browser.");
  }
}

function geocodePosition(position) {
  var latlng = {
    lat: position.coords.latitude,
    lng: position.coords.longitude
  };

  // GB is the country code for United Kingdom of Great Britain and Northern Island
  // SE is for Sweden
  var specialCaseCountries = ['GB', 'SE'];
  var specialCaseState = ['Brooklyn'];
  var geocoder = new google.maps.Geocoder();
  var map;

  // reverse geocode the geographical coordinates from the Geolocation API
  geocoder.geocode({
    'location': latlng
  }, function(results, status) {
    // variable for the selected address that corresponds as the city
    var city;
    if (status === 'OK') {
      results.map(function(k, i) {
        results[i].address_components.map(function(a, b) {
          // checking if the result is included on the specialCaseCountries
          if (specialCaseCountries.includes(a.short_name)) {
            if (results[i].types.includes('postal_town')) {
              console.log('formatted address: ', results[i].formatted_address);
              city = results[i];
            }
            // checking if the result is included on the specialCaseState
          } else if (specialCaseState.includes(a.short_name)) {
            if (results[i].types.includes('sublocality_level_1')) {
              console.log('formatted address: ', results[i].formatted_address);
              city = results[i];
            }
            // other addresses
          } else {
            if (results[i].types.includes('locality')) {
              console.log('formatted address: ', results[i].formatted_address);
              city = results[i];
            }
          }
        });
      });
      // create a map that's centered on the selected adddress' location 
      map = new google.maps.Map(document.getElementById('map'), {
        center: city.geometry.location,
        zoom: 10
      });
      // Set the viewport on the selected adddress' viewport
      map.fitBounds(city.geometry.viewport);

    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

请找到工作示例 here