I have been trying to put together two of the functionalities the GoogleMaps API offers for developers(Places Search and Geolocation)
Since I'm not very familiar with javascript, I'm not positive what could be the mistake I'm making. So far, the Places Search is totally functional (with a predetermined location) but not so the Geolocation (which should overwrite the predetermined location with the user's location).
Here you can take a look at my code.
<!DOCTYPE html>
<html>
<head>
<title>Place searches</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map {
height: 580px;
width: 680px;
border: 10px solid darkred;
padding: 5px;
margin: 25px;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
var map;
var infowindow;
function initMap() {
var pyrmont = {lat:43.364490, lng:-8.407406};
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
infowindow = new google.maps.InfoWindow({map:map});
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 2000,
type: ['gym']
}, callback);
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.');
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
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);
});
}
</script>
</head>
<body>
<header>
<h1>Encuentra tu gimnasio más próximo</h1>
</header>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=***MY_KEY***&libraries=places,geometry&callback=initMap" async defer></script>
</body>
</html>
Any help would be very much appreciated.
There seems te be an error with the casing of the infoWindow variable.
It's declared like this:
var infowindow;
But in the callback for navigator.geolocation.getCurrentPosition is used with different casing:
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
This error should have been shown in the browser's development tools console.
Related
I am creating a webpage, in which it first get user location & then update map with user current location by showing a marker to user where he is now. But i want to get user location continuously after 500 milliseconds, But it is showing popup to user again & again to allow his location. But i want that if a user allow previous then popup will not shown to him again. Below is my for that.
<html>
<head>
<title>Map with live marker</title>
<meta name="viewport" content="initial-scale=1.0">
</head>
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<body>
<div id="map"></div>
<script>
var lat=0;
var lng=0;
var map;
function getUserlocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
lng = position.coords.longitude;
// initMap();
console.log(lat,lng);
});
} else {
alert("Geolocation is not supported by this browser.");
}
}
function initMap() {
var myLatLng = {lat: lat, lng: lng};
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: lat, lng: lng},
zoom: 30
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
setInterval(function(){
getUserlocation();
},500);
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=Apikey"></script>
</body>
</html>
Can anyone please help me to solve this issue?
I was thinking of something like this:
Didn't test it let me know if it works ;-)
<html>
<head>
<title>Map with live marker</title>
<meta name="viewport" content="initial-scale=1.0">
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
var marker;
if (navigator.geolocation) {
// watch for user movement
navigator.geolocation.watchPosition(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
console.log(lat,lng);
var myLatLng = {lat: lat, lng: lng}
initMap(myLatLng);
});
} else {
alert("Geolocation is not supported by this browser.");
}
function initMap(myLatLng) {
// create the map if it doesn't exist yet
if(!map) {
map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
zoom: 30
});
}
// optional for centering the map on each user movement:
else {
map.setCenter(myLatLng)
}
// create the marker if it doesn't exist yet
if(!marker) {
marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
} else {
// update the markers position
marker.setPosition(myLatLng);
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=Apikey"></script>
</body>
</html>
EDIT
Just tested it and had the same problem than you, when just drag and dropping the html file into the browser. It seems, that the browser doesn't set the permission for a local file.
Running a local web server like serve solves the problem.
I'm coding JS app which will do this things
Find my location(I did this)
Find specified ATM(well I didn't figure how to find around my radius)
To list all found ATMs and sort them by distance
For this I need rankBy but I don't know how to use it.I looked on internet,where nearly everyone talks about that but no one don't show how to use.
Does someone can help mi to set my radius and in that radius to show ATMs and sort them by distance?
here is code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Marker Animations</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
function initMap() {
var map, infoWindow,service,infoWindow1;
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 12
});
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.open(map);
map.setCenter(pos);
var marker = new google.maps.Marker({
map: map,
position: pos,
draggable: true,
animation: google.maps.Animation.DROP,
});
marker.addListener('click', toggleBounce);
function toggleBounce() {
if (marker.getAnimation() !== null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
}, 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);
}
infoWindow1 = new google.maps.InfoWindow;
service = new google.maps.places.PlacesService(map);
map.addListener('idle', performSearch);
function performSearch() {
var request = {
bounds: map.getBounds(),
keyword: 'telenor atm',
};
service.radarSearch(request, callback);
}
function callback(results, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
console.error(status);
return;
}
for (var i = 0, result; result = results[i]; i++) {
addMarker(result);
}
}
function addMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: {
url: 'https://developers.google.com/maps/documentation/javascript/images/circle.png',
anchor: new google.maps.Point(10, 10),
scaledSize: new google.maps.Size(30, 37)
}
});
google.maps.event.addListener(marker, 'click', function () {
service.getDetails(place, function (result, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
console.error(status);
return;
}
infoWindow1.setContent(result.name);
infoWindow1.open(map,marker);
});
});
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCW8gRR1ITJDx4F-rVpkBSetftu32XO2P0&callback=initMap&libraries=places,visualization" async defer></script>
</body>
</html>
I'm building JS app.Tasks are:
1.Locate me and find nearest ATMs of specified bank
2.Then sort what she found in list.Sort by distance from me.
3.On the end are some design like a image on marker of store etc..
Well I did to locate me and to show me locations of ATMs
But I can't figure out to create list and sort that ATMs by distance from me
Does someone can help me
My code is
<!DOCTYPE html>
<html>
<head>
<title>Place searches</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
var map;
var infowindow;
function initMap() {
var pyrmont = {lat: -33.867, lng: 151.195};
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 500,
type: ['store']
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
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);
});
}
</script>
</head>
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCW8gRR1ITJDx4F-rVpkBSetftu32XO2P0&libraries=places&callback=initMap" async defer></script>
Thanks
I wrote a little html page in order to display pushpins on a map.
I give some address to my webpage, then I use the geocoding() and i display pushpins.
Then, I would like to add the google.maps.Animation.DROP with a timeout like explained on the Google Maps API page. ( https://developers.google.com/maps/documentation/javascript/examples/marker-animations-iteration?hl=fr)
On the Google Maps API page, the sample code directly uses the coordinates. It's simple.
In my case, I need to use before the geocoding() to get points, then display the pushpins.
I really don't understand but I'm unable to use this Drop animation with timeout using geocoding. I used the debugger view in Chrome, and I don't understand.
Here is my code, i tried to do as simple as possible :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
width:100%;
height:100%;
}
</style>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps</title>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAs4c8xnkxcZNRK6yQt-Y21N1L3mT1AFfE&callback=initMap">
</script>
</head>
<body>
<div id="map" ></div>
<noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b>
However, it seems JavaScript is either disabled or not supported by your browser.
To view Google Maps, enable JavaScript by changing your browser options, and then
try again.
</noscript>
<script type="text/javascript">
//<![CDATA[
var infoWindow;
var map;
var geocoder;
var bounds;
var TbCoordonnees = [];
var TbMarkers = [];
var AdresseTiersTb = [];
function initMap()
{
geocoder = new google.maps.Geocoder();
var optionsCarte = {
zoom: 8,
center: new google.maps.LatLng(48.5, 2.9),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), optionsCarte);
bounds = new google.maps.LatLngBounds();
infoWindow = new google.maps.InfoWindow({});
// EXAMPLE :
AdresseTiersTb.push("39 Boulevard de Courtais, 03100 Montluçon");
AdresseTiersTb.push("Place de l'Hôtel de ville, 13100 Aix-en-Provence");
AdresseTiersTb.push("55 Rue du Faubourg Saint-Honoré, 75008 Paris");
AdresseTiersTb.push("Place des Buisses, 59000 Lille");
for (var i = 0; i < AdresseTiersTb.length; i++)
{
geocodeAddress(AdresseTiersTb[i],i*200);
}
}
function geocodeAddress(address,timeout)
{
geocoder.geocode(
{'address': address},
function(results, status)
{
if((results != null) && (status == google.maps.GeocoderStatus.OK))
{
var marker = createMarker(address,timeout,results);
}
else
{
alert("geocode failed on "+address+", status="+status);
}
}
);
}
function createMarker(address,timeout,results)
{
var marker;
window.setTimeout(function() {
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,animation: google.maps.Animation.DROP
});},timeout);
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds)
map.panToBounds(bounds);
map.setCenter(bounds.getCenter());
var infocontent = address;
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(infocontent);
infoWindow.open(map, marker);
});
return marker;
}
function listenMarker (marker, info)
{
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(info);
infoWindow.open(map, this);
});
}
</script>
The problem is the var marker appear to be undefined, so no pushpins once pushpin is displayed instead of three. I don't know why but when I look in debug mode I don't understand how the geocoding is executed. Very strange.
You can't return a useful value of the marker variable from the asynchronous setTimeout callback function (where it is created and added to the map). The function returns the variable immediately (before it is defined by the callback of the setTimeout call (which runs some time later). The marker is also not defined when you are adding the click event listener.
proof of concept fiddle
code snippet:
var infoWindow;
var map;
var geocoder;
var bounds;
var TbCoordonnees = [];
var TbMarkers = [];
var AdresseTiersTb = [];
function initMap() {
geocoder = new google.maps.Geocoder();
var optionsCarte = {
zoom: 8,
center: new google.maps.LatLng(48.5, 2.9),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), optionsCarte);
bounds = new google.maps.LatLngBounds();
infoWindow = new google.maps.InfoWindow({});
// EXAMPLE :
AdresseTiersTb.push("Versailles, FR");
AdresseTiersTb.push("Paris, FR");
AdresseTiersTb.push("Sens, FR");
for (var i = 0; i < AdresseTiersTb.length; i++) {
geocodeAddress(AdresseTiersTb[i], i * 200);
}
}
function geocodeAddress(address, timeout) {
// function closure on address.
geocoder.geocode({
'address': address
},
function(results, status) {
if ((results != null) && (status == google.maps.GeocoderStatus.OK)) {
createMarker(address, results[0].geometry.location, timeout);
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds)
} else {
alert("geocode failed on " + address + ", status=" + status);
}
}
);
}
function createMarker(address, latLng, timeout) {
// function closure on address, latLng
window.setTimeout(function() {
var marker = new google.maps.Marker({
map: map,
position: latLng,
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(marker, 'click', (function(marker, address) {
// function closure on marker, address
return function() {
infoWindow.setContent(address);
infoWindow.open(map, marker);
}
})(marker, address));
}, timeout);
}
function listenMarker(marker, info) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(info);
infoWindow.open(map, this);
});
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
Just as the title states. I have tried google.maps.places.RankBy.PROMINENCE (default) and setting the radius to 50000 and am returned 20 results. But when I try the exact same search, minus the radius as according to the documentation, and using google.maps.places.RankBy.DISTANCE I am only returned 3 results in a short radius of my locations. Can someone explain why this happens and how to get a nearby search by distance with full results. Maybe I am just doing something wrong. Thanks.
The code bellow returns 20 results using google.maps.places.RankBy.PROMINENCE
var map;
var infowindow;
function initMap() {
var location = {lat: 43.139387, lng: -80.264425};
map = new google.maps.Map(document.getElementById('map'), {
center: location,
zoom: 9
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: location,
radius: 50000,
types: ['police'],
// rankBy: google.maps.places.RankBy.DISTANCE
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
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);
});
}
<!DOCTYPE html>
<html>
<head>
<title>Place searches</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 src="https://maps.googleapis.com/maps/api/js?sensor=false&signed_in=true&libraries=places&callback=initMap" async defer></script>
</body>
</html>
The code bellow returns only 3 results when using google.maps.places.RankBy.DISTANCE
var map;
var infowindow;
function initMap() {
var location = {lat: 43.139387, lng: -80.264425};
map = new google.maps.Map(document.getElementById('map'), {
center: location,
zoom: 9
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: location,
// radius: 50000,
types: ['police'],
rankBy: google.maps.places.RankBy.DISTANCE
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
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);
});
}
<!DOCTYPE html>
<html>
<head>
<title>Place searches</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 src="https://maps.googleapis.com/maps/api/js?sensor=false&signed_in=true&libraries=places&callback=initMap" async defer></script>
</body>
</html>
The radius attribute for the PROMINENCE code may have an effect on the search result. And based on the Places documentation, it can be affected by Google's index, global popularity, etc.
For DISTANCE, the optional attributes such as keyword, name, and types are now required.
Hope this clarifies some points regarding your issue.