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

前端 未结 7 1417

I am writing JavaScript code using Google Maps API.

map = new google.maps.Map2(document.getElementById(\"map_canvas\"));
map.setCenter(new google.maps.LatLng         


        
7条回答
  •  暖寄归人
    2020-12-25 14:22

    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:

    
     
     
         
        Google Maps API Geocoding Demo 
         
       
       
    
        

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

    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.

提交回复
热议问题