使用google maps API,我们如何使用map.setCenter函数将当前位置设置为默认设置位置?

时间:2010-05-17 17:02:19

标签: javascript google-maps geolocation

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

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

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

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

7 个答案:

答案 0 :(得分:15)

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

答案 1 :(得分:10)

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

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

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

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

不幸的是,目前只有少数现代浏览器支持GeoLocation API。因此,您还可以考虑使用服务器端解决方案,使用MaxMind's 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>

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

Render google map in based on selected location

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

答案 2 :(得分:8)

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

有几个主题有同样的问题......

答案 3 :(得分: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();

答案 4 :(得分:0)

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

答案 5 :(得分:-1)

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

答案 6 :(得分:-1)

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