How to get Client location using Google Maps API v3? - javascript

How do you get Client location using Google Maps API v3? I tried the following code but kept getting the "google.loader.ClientLocation is null or not an object" error. Any ideas why ??
if (google.loader.ClientLocation) {
alert(google.loader.ClientLocation.latitude+" "+google.loader.ClientLocation.longitude);
}
Thank You

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>

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/

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

No need to do your own implementation. I can recommend using geolocationmarker from google-maps-utility-library-v3.

It seems you now do not need to reverse geocode and now get the address directly from ClientLocation:
google.loader.ClientLocation.address.city

Related

Capture address using HTML5 Geolocation

I have this working code which is capturing a visitor's current location so I want it to display the visitor's current address into a textbox once the visitor accept to share the location
<div>
<input id="address" type="text" style="width:600px;"/>
</div>
<div id="map"></div>
<script>
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -13.961800, lng: 33.7693036},
zoom: 15
});
infoWindow = new google.maps.InfoWindow;
// 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.');
infoWindow.open(map);
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.');
infoWindow.open(map);
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=[MY API KEY HERE]&callback=initMap">
</script>
In order to do so, you need to use another API of Google which is called Geocoding.
https://developers.google.com/maps/documentation/geocoding/start?hl=fr
Indeed, you'll only retrieve GPS Coords with the geolocation API which is just 2 numbers.
Thanks to reverse geocoding, you can retrieve physical adress of the user with the coords X & Y.
Hope it'll help you out !

Google Maps Javascript map center update

All,
I am by no means a JavaScript programmer, mostly reusing/re-purposing snippets from here and there to accomplish things. I'm currently trying to work around a Google maps limitation, which is that the maps aren't styleable (AFAICT) unless you roll your own. I have a working HTML page, which contains a Google map, which correctly uses the Google maps styles and geolocation to set the map center to the user's location.
My question:
How can I keep the map centered on the user's location if their location changes while the page is open?
Search as I may I have been unable to find an example where the geolocation is updated through JavaScript. It could be that this isn't possible, it could be that Google's API documentation is weak, or possibly my Google-fu stinks. Possibly all three.
My code (taken almost verbatim from the Google Maps docs):
<body>
<div id="map"></div>
<script>
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 38.391677, lng: -97.661646},
zoom: 17,
styles: [...]
});
infoWindow = new google.maps.InfoWindow;
// 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.');
infoWindow.open(map);
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.');
infoWindow.open(map);
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=********************************&callback=initMap">
</script>
</body>
To detect changes in geolocation you can use the watchPosition method. (Not supported in all browsers though).
You can then call setCenter when you have a new set of co-ordinates, and it will centre the map for you.
There's a blog post here that seems to describe exactly what you are trying to do.
Assuming the initial setting of the center to the current location works, you could simply wrap the code in a setInterval call to repeatedly set the center every few seconds:
if (navigator.geolocation) {
setInterval(function() {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
}, 1000); // 1000 = number of milliseconds after which to repeat the call, i.e. 1 second
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
I'm not sure, if you really want the infoWindow and error message to be displayed on every call, but the basics are there.

How to center Google Maps to the current lat and long of the user?

I'm trying to create a Store Locator with Google Maps.
I would like to center the map dynamically on the lat and long of the user.
Could someone help me in the right direction?
I already read the Google Developer Guide.
I can get the variables with help from W3Schools:
https://www.w3schools.com/html/html5_geolocation.asp
But I can't get the vars in the const map:
function initMap() {
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
console.log(latitude);
console.log(longitude);
}
getLocation();
// Create the map.
const map = new google.maps.Map(document.getElementsByClassName('map')[0], {
zoom: 7,
center: {lat: latitude, lng: longitude},
styles: mapStyle
});
Browser gives an Uncaught ReferenceError: latitude is not define`
Can someone help me in the right direction?
The Function below finds the location of the user, set a infowindow and center the map to that location. try to implement it to your app.
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
infoWindow = new google.maps.InfoWindow;
// 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.');
infoWindow.open(map);
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.');
infoWindow.open(map);
}
and you can find the details here.

Geolocation doesn't work in browser

<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see the error "The Geolocation service
// failed.", it means you probably did not give permission for the browser to
// locate you.
function initMap() {
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.');
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
When I tried to run the page, it displayed a message which is this page didn't load Google map correctly. See the JavaScript. The browser already had a permission to access my location. But I don't know what is the problem?
Your code seems good, but you have forgotten to substitute the API KEY. So, you have to obtain a KEY in this page: https://developers.google.com/maps/documentation/javascript/get-api-key
and then subsitute the KEY in YOUR_API_KEY:
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">

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

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?
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);
}
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&v=2&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.
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...
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();
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'
});
}
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);
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>

Categories