Google Maps Javascript map center update - javascript

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.

Related

Troubleshooting Google maps JavaScript API / navigator.geolocation error that wont add a marker location inside a park

Im trying to get my geolocation to show inside a nearby park/conservancy. In this instance when im on the local hiking trail. When using the Google maps Javascript API and the navigator.geolocation from the browser if I'm walking in the street or anywhere inside the typical google maps neighborhood (the grayish areas on google maps) the results are accurate but the second i step into the park/conservancy (a green area) the location stops exactly at the street as if there were a forcefield. The location marker will follow my route along the street like a mime as i walk down the trail but will not cross the plane of the park.
I personally am at a loss as this even happened when i used the Google "find your location" example from the documents for the API. So for this i submit their example as i have followed it to the fullest but wonder if anyone knows a workaround to get my location to show accurately in the park or a reason to why this might be happening?
Phone settings that I have tried on my Samsung Galaxy S21 Ultra are:
WI-FI off, Bluetooth Off, WI-Fi Scanning off and on, Bluetooth scanning off and on.
let map: google.maps.Map, infoWindow: google.maps.InfoWindow;
function initMap(): void {
map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: -34.397, lng: 150.644 },
zoom: 6,
});
infoWindow = new google.maps.InfoWindow();
const locationButton = document.createElement("button");
locationButton.textContent = "Pan to Current Location";
locationButton.classList.add("custom-map-control-button");
map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton);
locationButton.addEventListener("click", () => {
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position: GeolocationPosition) => {
const pos = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
infoWindow.setPosition(pos);
infoWindow.setContent("Location found.");
infoWindow.open(map);
map.setCenter(pos);
},
() => {
handleLocationError(true, infoWindow, map.getCenter()!);
}
);
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter()!);
}
});
}
function handleLocationError(
browserHasGeolocation: boolean,
infoWindow: google.maps.InfoWindow,
pos: google.maps.LatLng
) {
infoWindow.setPosition(pos);
infoWindow.setContent(
browserHasGeolocation
? "Error: The Geolocation service failed."
: "Error: Your browser doesn't support geolocation."
);
infoWindow.open(map);
}

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 API & HTML5 geolocation, map.getCenter() giving wrong value

I'm trying to write the users current location to a database but after the HTML 5 geolocation I get the wrong value for map.getCenter(). Here's the relevant code (from 2 different Google development sites). The complete code can be found at https://aslett.net/gmaps.
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 17,
mapTypeId: 'roadmap'
});
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());
});
var latlng = map.getCenter();
var url = "add_marker.php?lat=" + latlng.lat() + "&lng=" + latlng.lng() + "&type=red";
downloadUrl(url, function(data, responseCode) {
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
The problem is the line (near the bottom)...
var latlng = map.getCenter();
...I was expecting it to give me the co-ordinates that were set in the HTML5 geolocation line (4 lines up)...
map.setCenter(pos);
...but it gives me the value that was set by (near the top)...
center: new google.maps.LatLng(47.6145, -122.3418),
I also tried to get the position using...
var latlng = infoWindow.getPosition();
... but that didn't work (am new to this map stuff and am grabbing at straws).
The line var latlng = map.getCenter();, which you have added to Google's example code on https://developers.google.com/maps/documentation/javascript/examples/map-geolocation, is executed BEFORE the getCurrentPosition() function. So at that time this variable is set, the map's center is still where you have defined it at the top. After that, the getCurrentPosition() method is fired.
You should add your extra lines of code into the getCurrentPosition() function.

Detect current location & calculate distance with predefined location for website

I want user's current location to be detected by browser and with predefined location from textbox or label that should calculate total distance between two places. It is something like zomato shows in any restaurant list. I want to know how can I do it for my vb.net website? Please suggest me any links which suggest this things.
to get the user's current location you'll need to use Geolocation API.
to get current Address from coordinates you'll need to use Geocoder API
To use Google Maps and these API you will have to generate an API Key for Google Cloud Platform. And make sure to enable the above mentioned API's for the generated API Key.
Example Code:
var map, infoWindow;
// initialize a map with given coordinates (call it in HTML!).
function initMap() {
var egypt = new google.maps.LatLng(26.8206, 30.8025);
infoWindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById('map'), {
center: egypt,
zoom: 6,
});
getCurrentLocation();
getCurrentAddress(map, infoWindow, pos);
}
// set Map to current location.
function getCurrentLocation() {
if (navigator.geolocation) {
// Browser supports geolocatin (get current location).
navigator.geolocation.getCurrentPosition(
function (position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
infoWindow.setPosition(pos);
infoWindow.setContent('You are here.');
infoWindow.open(map);
map.setZoom(15);
map.setCenter(pos);
getCurrentAddress(map, infoWindow, 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: Unable to get your current location.'
: "Error: Your browser doesn't support geolocation."
);
infoWindow.open(map);
}
// get current Address from coordinates (pos) using Geocoder API.
function getCurrentAddress(map, infowindow, pos) {
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({ latLng: pos }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0].formatted_address);
// create marker at current position.
const marker = new google.maps.Marker({
position: pos,
map: map,
});
// open an infoWindow above marker & set its content to current address.
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
console.log('Geocoding failed: ' + status);
}
});
}
}
#StupidRomeo Use Geolocation, Custom Controls, Autocomplete API(optional) , Distance Matrix Service.
Geolocation for attempting to locate the user's current user. Here is an example Note that this is upon accepting the user's that his/her location to known.
The Google Maps Geolocation API returns a location and accuracy radius based on information about cell towers and WiFi nodes that the mobile client can detect. This document describes the protocol used to send this data to the server and to return a response to the client.
An input box with (autocomplete api) helps ease the user's convience to find a correct location that Google Maps would find. Here is an example provided in the document. Using the autocomplete feature of the Google Places API to help users fill in the information.
Then lastly would be fetching the two point using the custom button and will call the Distance Matrix Service
Sample response of Distance Matrix Service API:
"rows": [ {
"elements": [ {
"status": "OK",
"duration": {
"value": 70778,
"text": "19 hours 40 mins"
},
"distance": {
"value": 1887508,
"text": "1173 mi"
}
}

How to get Client location using Google Maps API v3?

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

Categories