Google maps API & HTML5 geolocation, map.getCenter() giving wrong value - javascript

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.

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.

Nearby Places Google Maps Places API

First of all, I just started with JavaScript, so I'm not really good at it. I am making an app, using the Google Maps Places API, in which you can push a button and get your location, push another button and get nearby places (for example stores or bars) based on your location. Getting the location of the device works, but my code doesn't display the nearby places. It does go to the location, but it doesn't show the markers of the nearby places. I don't know what is going wrong, but I think it might have to do with the code for the markers or with the sequence of the code.
I am using Intel XDK (HTML5 + Cordova and the App Designer) and the Google Maps Places API. Right now it all happens when one button (with id="myloc-btn") is pushed, but (if both the location and the nearby places work) I want to seperate them in two buttons, one to show the location and one to show the nearby places.
Below is my javascript code. I have commented out the marker for the location of the device I originally had, because I thought it might be in the way of the markers for the nearby places.
Anyone know what's wrong or can help me?
Thanks in advance!
---UPDATE---
I tried the search nearby places from the Google Maps documentation (https://developers.google.com/maps/documentation/javascript/examples/place-search), with a set location (I basically copied and pasted the code), but that doesn't work either. Again it goes to the right location, but it doesn't display any markers. I tried it both in the simulator and on my phone, but it both has the same result. I don't know why the markers don't show
var map;
var service;
var infoWindow;
var pos;
var marker = [];
//var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
//var labelIndex = 0;
function register_event_handlers() {
$(document).on("click", "#myloc-btn", function(evt) {
initMap();
});
function initMap() {
map = new google.maps.Map(document.getElementById('gmap'), {zoom: 14});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
//addMarker(pos, map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
var request = {
location: pos,
radius: 5000,
type: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
/*
function addMarker(location, map) {
var marker = new google.maps.Marker({
map: map,
// Define the place with a location, a query string and a label.
place: {
location: location,
query: 'This is my location'
},
label: labels[labelIndex++ % labels.length],
});
// Construct a new InfoWindow.
var infoWindow = new google.maps.InfoWindow({
content: 'Here I am!'
});
// Opens the InfoWindow when marker is clicked.
marker.addListener('click', function() {
infoWindow.open(map, marker);
});
}
*/
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
document.addEventListener("app.Ready", register_event_handlers, false);
})();
In the callback provided to getCurrentPosition(), you're setting pos. However, this callback will get called after the phone has determined the location, i.e. at some random point in the future. Which is long after you're trying to use that pos in your request for the places. You need to move the places code in its own function, then call it while passing the map and pos, after you have centered the map. Almost exactly what you already did with addMarker().

set marker google maps javascript api

I am trying to create with the google maps javascript api the following: After page loading a marker should become set at the users location, what now works. After that should where the user click on the map a marker become added and the previous one deleted. One marker should be only on the map. Now the previous marker wont become deleted and other become added what I dont want. What can I do to have always one marker on the map?
var markers = [];
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 7
});
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
};
map.setCenter(pos);
// This event listener will call addMarker() when the map is clicked.
map.addListener('click', function(event) {
deleteMarkers();
addMarkers(event.latLng);
});
addMarkers(pos);
// Adds a marker to the map and push to the array.
function addMarkers(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
markers.push(marker);
}
// Sets the map on all markers in the array.
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setMapOnAll(null);
}
// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
clearMarkers();
marker = [];
}
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
Take a look here I believe you are close :)
you are just setting your markers array to be nothing , but not actaully clearing the marker

Categories