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

做~自己de王妃 提交于 2019-12-18 11:12:12

问题


I am writing JavaScript code using Google Maps API.

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.

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


回答1:


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

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



回答2:


I can think of two possible options.

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

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

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

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:

<!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:

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




回答3:


that already exists in the 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...




回答4:


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

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



回答5:


An updated version of @ceejayoz's answer:

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



回答6:


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



回答7:


Try this bro : I centered Indonesia using lat and 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>


来源:https://stackoverflow.com/questions/2851089/using-google-maps-api-how-can-we-set-the-current-location-as-the-default-set-lo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!