Javascript 使用谷歌地图 API,我们如何使用 map.setCenter 函数将当前位置设置为默认设置位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2851089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:10:39  来源:igfitidea点击:

Using google maps API, how can we set the current location as the default set location using map.setCenter function?

javascriptgoogle-mapsgeolocation

提问by HVS

I am writing JavaScript code using Google Maps API.

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

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

The above code sets the default location of the map canvas to Palo Alto.

上面的代码将地图画布的默认位置设置为 Palo Alto。

How can we write the script in such a way that the setCenter function automatically points to the current location of the client?

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

回答by ceejayoz

You can use the HTML5 GeoLocation API in browsers that support it.

您可以在支持它的浏览器中使用 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);
}

回答by Daniel Vassallo

I can think of two possible options.

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

First you may want to consider using the GeoLocation APIas ceejayoz suggested. This is very easy to implement, and it is a fully client-side solution. To center the map using GeoLocation, simply use:

首先,你可能要考虑使用地理位置API作为ceejayoz建议。这很容易实现,而且它是一个完全客户端的解决方案。要使用 GeoLocation 将地图居中,只需使用:

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

... inside the success()callback of the GeoLocation's getCurrentPosition()method.

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

Unfortunately only a few modern browsers are currently supporting the GeoLocation API. Therefore you can also consider using a server-side solution to resolve the IP address of the client into the user's location, using a service such as MaxMind's GeoLite City. Then you can simply geocode the city and country of the user inside the browser, using the Google Maps API. The following could be a brief example:

不幸的是,目前只有少数现代浏览器支持 GeoLocation API。因此,您也可以考虑使用服务器端解决方案,使用MaxMind 的 GeoLite City等服务将客户端的 IP 地址解析为用户的位置。然后,您可以使用 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>

Simply replace userLocation = 'London, UK'with the server-side resolved address. The following is a screenshot from the above example:

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

Render google map in based on selected location

根据选定的位置渲染谷歌地图

You can remove the marker by getting rid of the map.addOverlay(new GMarker(bounds.getCenter()));line.

您可以通过摆脱map.addOverlay(new GMarker(bounds.getCenter()));线条来移除标记。

回答by Txugo

that already exists in the google api:

已经存在于 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);
    }
}

There are several threads with the same question...

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

回答by Mas

This solution tries to get user location from browser first, if the user refused or any other error occurs it then gets the location from user's IP address

此解决方案首先尝试从浏览器获取用户位置,如果用户拒绝或发生任何其他错误,则从用户的 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);
};

and call it like:

并称之为:

mapUserLocation();

回答by user1012181

An updated version of @ceejayoz's answer:

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

回答by Eko Junaidi Salam

Try this bro : I centered Indonesia using lat and lng.

试试这个兄弟:我使用 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>

回答by nex

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