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>
Related
I'm using Google maps API and Google Places API to get the user's device current location and to retrieve the nearby restaurants, gyms, etc. from that location. I've checked the official google documentation and I've created this code:
html code:
<div id="map"> </div>
<script src="https://maps.googleapis.com/maps/api/js?key=I_REPLACED_MY_KEY_IN_HERE&libraries=places&callback=initMap" async defer ></script>
JAVASCRIPT:
var map;
var service;
var infowindow;
var pos;
var request;
var place;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
infoWindow = new google.maps.InfoWindow;
getLocation();
getNearByPlaces();
callback();
}
function getLocation(){
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
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());
}
infowindow = new google.maps.InfoWindow();
}
function getNearByPlaces(){
request = {
location: pos,
radius: '500',
query: 'restaurant'
};
service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
}
function callback(results, status){
if (status == google.maps.places.PlacesServiceStatus.OK){
for (var i =0; i<results.length; i++){
place = results[i];
}
}
}
I'm getting the map with the nearby places and the device current location, the problem is that I'm not getting only the restaurants as I specified in my request, I want to get restaurants only in 500 radius and to retrieve their latitudes and longitudes, getnearbyplaces and callback aren't doing anything.
The geolocation service is asynchronous. You need to call getNearByPlaces when the location is available, in the callback function for the geolocation service.
function getLocation() {
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
getNearByPlaces(pos); // depends on value of pos
// existing error handling...
proof of concept fiddle
code snippet:
var map;
var service;
var infowindow;
var pos;
var request;
var place;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 6
});
infoWindow = new google.maps.InfoWindow;
getLocation();
// getNearByPlaces();
// callback();
}
function getLocation() {
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
console.log("getLocation:" + pos.lat + "," + pos.lng);
var marker = new google.maps.Marker({
position: pos,
map: map,
icon: "http://maps.google.com/mapfiles/ms/micons/blue.png"
})
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
getNearByPlaces(pos);
}, function() {
console.log("calling handleLocationError(true)");
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
console.log("calling handleLocationError(false)")
handleLocationError(false, infoWindow, map.getCenter());
}
infowindow = new google.maps.InfoWindow();
}
function getNearByPlaces(pos) {
console.log("getNearByPlaces:" + pos.lat + "," + pos.lng);
request = {
location: pos,
radius: '500',
query: 'restaurant'
};
service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
console.log("callback received " + results.length + " results");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < results.length; i++) {
console.log(JSON.stringify(results[i]));
place = results[i];
var mark = createMarker(results[i]);
bounds.extend(mark.getPosition());
}
map.fitBounds(bounds);
} else console.log("callback.status=" + status);
}
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);
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: "http://maps.google.com/mapfiles/ms/micons/red.png"
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
return marker;
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initMap" async defer></script>
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.
I am working on Google map api [Here is my to find out near by restaurant. . . When I run this, I get only current location. I am not receiving any information related to restaurant data.
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 25.276987, lng: 55.296249 },
zoom: 15
});
var infoWindow = new google.maps.InfoWindow({ map: map });
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);
var marker = new google.maps.Marker({
map: map,
position: pos.getPlace().location
});
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: rak,
radius: 5500,
type: ['restaurant'] // not resturant
}, callback);
}, function () {
handleLocationError(true, infoWindow, map.getCenter());
});
}
else {
handleLocationError(false, infoWindow, map.getCenter());
}
}
Maybe you are encountering an error with the nearbySearch location tag. You didn't initiate the variable rak and it will return a null value.
Set the Script
<script
src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initMap"
async defer></script>
Initialize you variables
var map;
var infowindow;
var myPlace = {lat: 25.276987, lng: 55.296249 };
Call your nearBySearch
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location : myPlace,
radius : 5500,
type : [ 'restaurant' ]
}, callback);
Check the result of search and then create a marker for each found location
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);
});
}
You can find this code in this document, it will explain well the proper coding and how to use the api. Also here is the list of supported location type.
I hope this helps.
I am using the Google Maps Javascript API. The sample code; I think gets me close but doesn't accomplish what I hoped for.
I hard code a 'placeid'
I am hoping to bring in my current location instead.
I do bring in my current location in the sample code but the Infowindow information is hard coded.
I am hoping to learn how to bring in both the 'Current Location' marker and 'Infowindow' place information dynamically without the need to hard code it.
My broken script follows>>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 42.0491125,
lng: -92.91123340000001
},
zoom: 12
});
var infowindow = new google.maps.InfoWindow();
// var infoWindow = new google.maps.InfoWindow({map: map});
var service = new google.maps.places.PlacesService(map);
service.getDetails({
// I would like to bring in the current position not a static place id
placeId: 'EioxMDEgRSBNYWluIFN0LCBNYXJzaGFsbHRvd24sIElBIDUwMTU4LCBVU0E'
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
'lat lng: ' + place.geometry.location + '<br>' +
place.formatted_address + '</div>');
infowindow.open(map, this);
});
}
});
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('Home Point.');
map.setCenter(pos);
var marker = new google.maps.Marker({
title: 'Your current location',
map: map,
// title: 'Your current location'
});
}, 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>
</head>
<body>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js? key=YOUR_API_KEY&libraries=places&callback=initMap">
</script>
</body>
</html>
You could combine Geolocation service to determine the current location and then Reverse Geocoding to resolve address information (inc. place id) as demonstrated below
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 42.0491125, lng: -92.91123340000001 },
zoom: 12
});
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
};
resolvePlace(pos,
function (place) {
var marker = new google.maps.Marker({
title: place.formatted_address,
map: map,
position: pos
});
//infoWindow.setPosition(pos);
infoWindow.setContent(place.formatted_address);
map.setCenter(pos);
infoWindow.open(map,marker);
},
function (status) {
infoWindow.setPosition(pos);
infoWindow.setContent('Geocoder failed due to: ' + status);
});
}, function () {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function resolvePlace(pos, success, error) {
var geocoder = new google.maps.Geocoder;
geocoder.geocode({ 'location': pos }, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[0]) {
success(results[0]);
} else {
error('No results found');
}
} else {
error(status);
}
});
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap">
</script>
Plunker
I have a problem with plotting a route from my position to a certain position , I need to take my latitude and longitude of the origin variable and simply attached code to see if someone manages to solve
try to leave the values in other variables , leaving them in a marker , among other ...
<!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, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
// Note: This example requires that you consent to location sharing when
// prompted by your browser. If you see a blank space instead of the map, this
// is probably because you have denied permission for location sharing.
var map;
function initialize() {
var pos;
var latitud;
var longitud;
var dirinicial;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
//var hola = pos;
latitud = position.coords.latitude;
longitud = position.coords.longitude;
/* var marker = new google.maps.Marker({
position: pos,
map: map,
title: 'Hello World!'
});
*/
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
// content: 'Location found using HTML5.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
var request = {
origin:'Santiago',
destination: 'Rancagua',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsDisplay.setMap(map);
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
/* // Display the distance:
document.getElementById('distance').innerHTML +=
response.routes[0].legs[0].distance.value + " meters";
// Display the duration:
document.getElementById('duration').innerHTML +=
response.routes[0].legs[0].duration.value + " seconds";
*/
directionsDisplay.setDirections(response);
}
});
}
function GetAddress(latlang) {
var latlng = new google.maps.LatLng(latitud, longitud);
var geocoder = geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
dirinicial= results[1].formatted_address;
//alert("Location: " + results[1].formatted_address);
}
}
});
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
Thanks in advance
regards from chile!
I see several errors here. First, your error management displays an infowindow at a random location {lat:60, lng:105} that's not related to the user eventual position.
Second, your route request has fixed origin and destination (Santiago and Rancagua), disregarding the user's current location at all. You should instead wait for the HTML5 geolocation API to return something to use as origin.
I've simplified your code a bit, and got this working
var map;
function initialize() {
var pos;
var latitud;
var longitud;
var dirinicial;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var generateRoute=function(origin,destination) {
var request = {
origin:origin,
destination: destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsDisplay.setMap(map);
directionsService.route(request, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
};
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
var yourpositionmarker = new google.maps.Marker({position:pos, map:map});
infowindow.open(map,yourpositionmarker);
map.setCenter(pos);
generateRoute(pos, 'Rancagua');
});
} else {
// Browser doesn't support Geolocation
console.log('No geolocation API');
}
}
google.maps.event.addDomListener(window, 'load', initialize);