Google Places API sorting by radius or distance - javascript

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

Related

Move marker continuously as per user location

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.

Google not defined error

I am making a webpage with Google Maps API but I am getting "google not defined error"
How can I get rid of this?
How can I import Google or do something to make this piece of code work?
I want a program in which user will enter location and it shows marker there. but it is not working properly.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<h1>Perform Google Maps Search</h1>
<h3> Please enter the place you want to search</h3>
<input type="text" id="mapsearch" size="50"> <br>
<br>
<div id="map"></div>
<script>
var map;
function initMap() {
var myOptions = {
zoom:14,
navigationControl: true,
scaleControl: true,
panControl: true,
center: new google.maps.LatLng(43.6532,-79.3832),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'),myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(43.6532,-79.3832),
title:"Toronto"
});
marker.setMap(map);
}
var searchBox = new google.maps.places.SearchBox(document.getElementById('mapsearch'));
map.controls[google.maps.ControlPosition.TOP_CENTER].push(document.getElementById('mapsearch'));
google.maps.event.addListener(searchBox, 'places_changed', function() {
searchBox.set('map', null);
var places = searchBox.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i, place;
for (i = 0; place = places[i]; i++) {
(function(place) {
var marker = new google.maps.Marker({
position: place.geometry.location
});
marker.bindTo('map', searchBox, 'map');
google.maps.event.addListener(marker, 'map_changed', function() {
if (!this.getMap()) {
this.unbindAll();
}
});
bounds.extend(place.geometry.location);
}(place));
}
map.fitBounds(bounds);
searchBox.set('map', map);
map.setZoom(Math.min(map.getZoom(),12));
});
google.maps.event.addDomListener(window, 'load', init);
</script>
<script src="https://maps.googleapis.com/maps/api/js?key="Your_API_Key"&callback=initMap"
async defer></script>
</body>
</html>
initMap function should be closed at last you are closing it before
var searchBox = new google.maps.places.SearchBox(document.getElementById('mapsearch'));
So you are getting google undefined error.
Also you have add parameter &libraries=places to google map script src
working example
https://plnkr.co/edit/ngtGvuhDDZAnovwPnPXh?p=preview
// Code goes here
var map;
function initMap() {
var myOptions = {
zoom:14,
navigationControl: true,
scaleControl: true,
panControl: true,
center: new google.maps.LatLng(43.6532,-79.3832),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'),myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(43.6532,-79.3832),
title:"Toronto"
});
marker.setMap(map);
var searchBox = new google.maps.places.SearchBox(document.getElementById('mapsearch'));
map.controls[google.maps.ControlPosition.TOP_CENTER].push(document.getElementById('mapsearch'));
google.maps.event.addListener(searchBox, 'places_changed', function() {
searchBox.set('map', null);
var places = searchBox.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i, place;
for (i = 0; place = places[i]; i++) {
(function(place) {
var marker = new google.maps.Marker({
position: place.geometry.location
});
marker.bindTo('map', searchBox, 'map');
google.maps.event.addListener(marker, 'map_changed', function() {
if (!this.getMap()) {
this.unbindAll();
}
});
bounds.extend(place.geometry.location);
}(place));
}
map.fitBounds(bounds);
searchBox.set('map', map);
map.setZoom(Math.min(map.getZoom(),12));
});
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<h1>Perform Google Maps Search</h1>
<h3> Please enter the place you want to search</h3>
<input type="text" id="mapsearch" size="50"> <br>
<br>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAtaKPvRV8-ciYtnnzG3QI3CO7m4HJyhaI&libraries=places&callback=initMap"
async defer></script>
</body>
</html>
Most likely your google APIs have not loaded, when your script needs them - hence the "google not defined error". Move this before your script and drop the async defer - or do your script inside a "$( document ).ready"
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAtaKPvRV8-ciYtnnzG3QI3CO7m4HJyhaI&callback=initMap"
async defer></script>

I'm trying to make a restaurant locator app and can't get the markers to appear

I'm trying to get markers for restaurants to drop on my map and it's not working. Any help would be appreciated. Do I need to add a query method? I am trying not too as I'm going to let the location be static when finished. Here is my relevant code,
<script>
var map;
function initialize() {
var center = new google.maps.LatLng(37.422, -122.084058);
map = new google.maps.Map(document.getElementById('map'), {
center: center,
zoom: 13
});
var request = {
location: center,
radius: 8047,
types: ['restaurant']
};
var service = new google.places.PlaceService(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 createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
PlacesService needs an API_KEY.
var map;
var infowindow;
function initMap() {
var center = new google.maps.LatLng(37.422, -122.084058);
map = new google.maps.Map(document.getElementById('map'), {
center: center,
zoom: 13
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: center,
radius: 8047,
type: ['restaurant']
}, 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);
});
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<!DOCTYPE html>
<html>
<head>
<title>Place searches</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script>
</script>
</head>
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB1tbIAqN0XqcgTR1-FxYoVTVq6Is6lD98&libraries=places&callback=initMap" async defer></script>
</body>
</html>

Google Maps Api Nearby Search - Why does google.maps.places.RankBy.DISTANCE return fewer results?

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.

Nearby places in google maps APIs

I am trying to write a program in javascript related to finding my place by using google maps APIs and the browser navigator and then put a marker on the place.My code works properly for this part. But for the second part that I want to find the nearby places and put markers on them does not work and I cannot find the problem. It gives me an error about the map variable. It seems the code breaks and cannot get the map variable for performsearch function. Any idea would be highly appreciated?
The code is as below:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 75% }
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC2MndnCGBXqDolsrQYhNdVyXqsk0NRm8Q&sensor=true&libraries=places">
</script>
<script type="text/javascript" >
var map;
function handleSearchResults(results, status)
{
console.log(results);
document.write
if (status == google.maps.places.PlacesServiceStatus.OK)
{
for(var i = 0; i<results.length; i++)
{
var marker = new google.maps.Marker(
{
position: results[i].geometry.Location,
map:map,
icon: results[i].icon
});
}
}
}
function performSearch()
{
var request = {
bounds: map.getBounds(),
name: "McDonald's"
};
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, handleSearchResults(results, status));
}
function initialize(location)
{
var myLatlng = new google.maps.LatLng(location.coords.latitude, location.coords.longitude);
var mapOptions =
{
center: myLatlng,
zoom: 9
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var marker = new google.maps.Marker(
{
position: myLatlng,
map: map,
title: "My place"
});
service = new google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch());
}
$(document).ready(function()
{
navigator.geolocation.getCurrentPosition(initialize);
});
</script>
</head>
<body>
<div id="map-canvas"/>
</body>
</html>
There are several issues. Fixed code(modifications are commented inside):
var map;
function handleSearchResults(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var marker = new google.maps.Marker({
//typo: it must be location not Location
position: results[i].geometry.location,
map: map,
icon: results[i].icon
});
}
}
}
function performSearch() {
var request = {
bounds: map.getBounds(),
name: "McDonald's"
};
var service = new google.maps.places.PlacesService(map);
//use only the name of the function as callback-argument
service.nearbySearch(request, handleSearchResults);
}
function initialize(location) {
var myLatlng = new google.maps.LatLng(location.coords.latitude,
location.coords.longitude);
var mapOptions = {
center: myLatlng,
zoom: 9
};
//removed the var-keyword(otherwise map is not global accessible)
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "My place"
});
//again: use only the name of the function as callback-argument
service = new google.maps.event.addListenerOnce(map,
'bounds_changed',
performSearch);
}
$(document).ready(function () {
navigator.geolocation.getCurrentPosition(initialize);
});
But note: geolocating may fail, currently the map will never be initialized when it fails. You better separate the map-creation from the geolocating

Categories

Resources