【问题标题】:Using google maps API, how can we set the current location as the default set location using map.setCenter function?使用 google maps API,我们如何使用 map.setCenter 函数将当前位置设置为默认设置位置?
【发布时间】:2011-02-20 12:29:22
【问题描述】:

我正在使用 Google Maps API 编写 JavaScript 代码。

map = new google.maps.Map2(document.getElementById("map_canvas"));
map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);

以上代码将地图画布的默认位置设置为帕洛阿尔托。

如何编写脚本,让setCenter函数自动指向客户端的当前位置?

【问题讨论】:

  • GeoLocation API 是显而易见的答案。但是,即使 API 可用,浏览器端也可能需要一些时间才能获得位置修复。同时,您必须向用户显示一些临时位置,然后在位置固定后移动地图。这听起来像是一个 GUI 挑战,以使其感觉正确。如果可以接受大致位置,我喜欢 Daniel Vassallo 的解决方案。加载后移动地图对我来说是有问题的。

标签: javascript google-maps geolocation


【解决方案1】:

此解决方案首先尝试从浏览器获取用户位置, 如果用户拒绝或发生任何其他错误,则从用户的 IP 地址获取位置

mapUserLocation = () => {
  navigator.geolocation
    ? navigator.geolocation.getCurrentPosition(
        handlePosition,
        getLocationFromIP
      )
    : getLocationFromIP();
};

getLocationFromIP = () => {
  fetch("http://ip-api.com/json")
    .then(response => response.json())
    .then(data => {
      data.lat &&
        data.lon &&
        updateUserPosition({
          lat: data.lat,
          lng: data.lon
        });
    })
    .catch(error => {
      console.log(`Request failed: `, error);
    });
};

handlePosition = position => {
  const userPos = {
    lat: position.coords.latitude,
    lng: position.coords.longitude
  };
  updateUserPosition(userPos);
};

updateUserPosition = position => {
  map.setCenter(position, 13);
};

然后这样称呼它:

mapUserLocation();

【讨论】:

    【解决方案2】:

    试试这个兄弟:我使用 lat 和 lng 以印度尼西亚为中心。

    $(document).ready(function () {
        var mapOptions = {
            zoom: 4,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
    
        var map = new google.maps.Map(document.getElementById('map'), mapOptions);
        
        var center = new google.maps.LatLng(-2.548926, 118.0148634);
        map.setCenter(center,4);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
    
    <div id="map" style="width:600px; height:450px"></div>

    【讨论】:

      【解决方案3】:

      @ceejayoz 答案的更新版本:

          if (navigator.geolocation) {
              navigator.geolocation.getCurrentPosition(success, error);
          } else {
              alert('geolocation not supported');
          }
          function error(msg) {
              alert('error: ' + msg);
          }
          function success(position) {
      
              var myLatlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
              var mapOptions = {
                  zoom: 12,
                  center: myLatlng,
                  scaleControl: false,
                  draggable: false,
                  scrollwheel: false,
                  navigationControl: false,
                  mapTypeControl: false
              }
      
      
              map = new google.maps.Map(document.getElementsByClassName('map-canvas')[0], mapOptions);
              marker = new google.maps.Marker({
                  position: myLatlng,
                  map: map,
                  title: 'Main map',
                  icon: iconBase + 'arrow.png'
              });
          }
      

      【讨论】:

        【解决方案4】:

        我能想到两种可能的选择。

        首先,您可能需要考虑将GeoLocation API 用作ceejayoz suggested。这很容易实现,它是一个完全客户端的解决方案。要使用 GeoLocation 使地图居中,只需使用:

        map.setCenter(new google.maps.LatLng(position.coords.latitude, 
                                             position.coords.longitude), 13);
        

        ...在 GeoLocation 的 getCurrentPosition() 方法的 success() 回调中。

        很遗憾,目前只有少数现代浏览器支持 GeoLocation API。因此,您也可以考虑使用服务器端的解决方案,将客户端的 IP 地址解析为用户的位置,使用诸如MaxMind's GeoLite City 之类的服务。然后,您可以使用 Google Maps API 在浏览器中简单地对用户所在的城市和国家/地区进行地理编码。以下可能是一个简短的示例:

        <!DOCTYPE html>
        <html> 
        <head> 
            <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
            <title>Google Maps API Geocoding Demo</title> 
            <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false"
                    type="text/javascript"></script> 
          </head> 
          <body onunload="GUnload()"> 
        
            <div id="map_canvas" style="width: 400px; height: 300px"></div> 
        
            <script type="text/javascript"> 
        
            var userLocation = 'London, UK';
        
            if (GBrowserIsCompatible()) {
               var geocoder = new GClientGeocoder();
               geocoder.getLocations(userLocation, function (locations) {         
                  if (locations.Placemark) {
                     var north = locations.Placemark[0].ExtendedData.LatLonBox.north;
                     var south = locations.Placemark[0].ExtendedData.LatLonBox.south;
                     var east  = locations.Placemark[0].ExtendedData.LatLonBox.east;
                     var west  = locations.Placemark[0].ExtendedData.LatLonBox.west;
        
                     var bounds = new GLatLngBounds(new GLatLng(south, west), 
                                                    new GLatLng(north, east));
        
                     var map = new GMap2(document.getElementById("map_canvas"));
        
                     map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
                     map.addOverlay(new GMarker(bounds.getCenter()));
                  }
               });
            }
            </script> 
          </body> 
        </html>
        

        只需将userLocation = 'London, UK' 替换为服务器端解析的地址即可。以下是上例的截图:

        您可以通过删除 map.addOverlay(new GMarker(bounds.getCenter())); 行来删除标记。

        【讨论】:

        • 感谢您的解释。我从来没有想过,常用的客户端组件(HTML5 之前)没有完全集成的地理定位支持。
        【解决方案5】:

        已经存在于 google api 中:

        if (GBrowserIsCompatible()) 
        {   
            var map = new google.maps.Map2(document.getElementById("mapdiv"));
        
            if (google.loader.ClientLocation) 
            {        
                var center = new google.maps.LatLng(
                    google.loader.ClientLocation.latitude,
                    google.loader.ClientLocation.longitude
                );
                var zoom = 8;
        
                map.setCenter(center, zoom);
            }
        }
        

        有几个线程有相同的问题...

        【讨论】:

          【解决方案6】:

          您可以在支持它的浏览器中使用 HTML5 GeoLocation API。

          if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(success, error);
          } else {
            alert('geolocation not supported');
          }
          
          function success(position) {
            alert(position.coords.latitude + ', ' + position.coords.longitude);
          }
          
          function error(msg) {
            alert('error: ' + msg);
          }
          

          【讨论】:

          • @npdoty 可能是 HTML5 品牌而不是规范与此处相关。
          • 请注意 map.setCenter 将不再接受缩放级别。如果您也想更改缩放级别,请使用 map.setZoom。
          【解决方案7】:
          map = new google.maps.Map2(document.getElementById("map_canvas"));
          pos = new google.maps.LatLng(37.4419, -122.1419);
          map.setCenter(pos, 13);
          map.panTo(pos);
          

          【讨论】:

          • 以上代码加载地图,并将位置设置为帕洛阿尔托。我的实际问题是,我们如何将位置自动设置为客户端的当前位置。
          • 哦,我明白了...为此您需要地理定位功能...开始阅读:mozilla.com/en/firefox/geolocation
          猜你喜欢
          • 2018-08-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-03-25
          • 1970-01-01
          • 2017-07-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多