设置初始中心并放大Google Maps API [英] Set initial center and zoom in google maps API

查看:150
本文介绍了设置初始中心并放大Google Maps API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们直接打开google map,则初始视图是我们的城市,该城市会缩放并适合整个屏幕.

If we open google map directly, the initial view is the our city, the city is zoomed and fitted in the whole screen.

如果我们基于google maps API(不设置center和zoom参数)创建地图网络应用,则初始视图为空白.

If we create a map web app based on google maps API (without setting the center and zoom parameters), the initial view is blank.

问题是:如何使地图网络应用的行为与Google地图相同(例如,在整个屏幕上都显示用户所在城市时显示初始地图视图)?

The question is: how to make the map web app behave the same as google map (eg. display initial map view as the user's city being fitted in the whole screen)?

期待答案,并期望尽可能少的代码.

Looking forward to the answer, and expect as less code as possible.

对于Bing Maps API,无需设置地图的中心和缩放比例即可在视图中显示城市.

For Bing Maps API, the city is fitted in view without setting the center and zoom of the map.

推荐答案

您提到希望将地图最初设置在用户所在的城市.基于此用例,我们有必要首先了解用户所在的城市.一种检测方法是使用HTML5的Geolocation API.

You mentioned that you want the map to be initially set on the user's city. Based on this use case, it is necessary for us to know first which city is our users at. One way to detect that is by using HTML5's Geolocation API.

我了解您会在弹出窗口中询问是否要烦人的权限,但是请注意,正如Geolocation API的文档(第4.1项)

I understand that you find the pop up asking for a permission to be annoying, but note that as stated in Geolocation API's doc (Item 4.1)

未经用户的明确许可,用户代理不得将位置信息发送到网站.

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

这就是为什么弹出窗口要求权限的原因.

This is why the pop ups asking for permissions are required.

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

Assuming that you are fine with it (you can always opt to use other user location detection strategy if you wish), then, after getting your target user's location (in the form of geographical coordinates), you can use Geocoding API to reverse geocode it. This will give us a list of addresses that were matched against these coordinates.

从此地址列表中,您可以选择与其城市相对应的地址.请注意,对于这部分, 您可能需要使用不同的组件集来与不同区域中使用的地址格式保持一致.

From this list of addresses, you could select the address which correspond to its city. Note that for this part, you may need to use different sets of components to align with the address formats used in different regions.

按照此 doc ,类型为locality的地方表示合并的城市或城镇政治实体.

As per this doc, places with a type locality indicates an incorporated city or town political entity.

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

However, on some cases like in UK and in Sweden, the component to display the city is postal_town. Brooklyn is another special case as it uses sublocality_level_1 to represent the city. I'm taking these special cases into consideration for my code sample below.

选择城市地址后,您可以获取其locationviewport并将其用于要实例化的地图中.

After selecting the city address, you could get its location and viewport and use that in the map that you will instantiate.

但是请根据您的用例随意修改以下代码示例:

But please feel free to modify the code sample below based on your use case:

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

请在此处

这篇关于设置初始中心并放大Google Maps API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆