How to get Client location using Google Maps API v3?
Solution 1:
Try this :)
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
function initialize() {
var loc = {};
var geocoder = new google.maps.Geocoder();
if(google.loader.ClientLocation) {
loc.lat = google.loader.ClientLocation.latitude;
loc.lng = google.loader.ClientLocation.longitude;
var latlng = new google.maps.LatLng(loc.lat, loc.lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
alert(results[0]['formatted_address']);
};
});
}
}
google.load("maps", "3.x", {other_params: "sensor=false", callback:initialize});
</script>
Solution 2:
A bit late but I got something similar that I'm busy building and here is the code to get current location - be sure to use local server to test.
Include relevant scripts from CDN:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&signed_in=true&callback=initMap">
HTML
<div id="map"></div>
CSS
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
JS
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
DEMO
https://jsfiddle.net/ToreanJoel/4ythpy02/
Solution 3:
I couldn't get the above code to work.
Google does a great explanation though here: http://code.google.com/apis/maps/documentation/javascript/basics.html#DetectingUserLocation
Where they first use the W3C Geolocation method and then offer the Google.gears fallback method for older browsers.
The example is here:
http://code.google.com/apis/maps/documentation/javascript/examples/map-geolocation.html
Solution 4:
No need to do your own implementation. I can recommend using geolocationmarker
from google-maps-utility-library-v3.