Bring in Google maps 'infowindow' information for current location - javascript

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

Related

How to change Google Maps info window to a geolocation marker

I followed a tutorial by Google https://developers.google.com/maps/documentation/javascript/geolocation so I could display the users position on a map. It currently looks like this with an info window:
However I would like to display a geolocation marker instead of the info window:
Here is my code:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.520008, 13.404954)
};
infoWindow = new google.maps.InfoWindow;
map = new google.maps.Map(document.getElementById("map"), mapOptions);
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);
}
Any help on how to change it from an info window to geolocation marker would be great. Thanks in advance.
To display location with marker in Google maps, you can try this:
var map = new google.maps.Map(document.getElementById("map"), {
center: {lat: 52.520008, lng: 13.404954},
zoom: 8,
mapTypeId: 'roadmap'
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(52.520008, 13.404954),
map: map,
/*if you want to custom marker icon, you can set icon path here*/
icon: 'your_icon_url',
/* if you don't want to enable dragging, just remove this property */
draggable: true
});
// if you enable dragging, you can initialize this event
// to get latitude, longitude and address
google.maps.event.addListener(marker, 'dragend', function (marker) {
var latLng = marker.latLng;
var currentLatitude = latLng.lat();
var currentLongitude = latLng.lng();
var geocoder = new google.maps.Geocoder;
var latlng = { lat: currentLatitude, lng: currentLongitude };
geocoder.geocode({ 'location': latlng }, function (results, status) {
if (status === 'OK') {
// address
console.log(results);
} else {
console.log('Geocoder failed due to: ' + status);
}
});
});
Note: To work with places in Google maps, you need to require libraries=places as a parameter inside the url:
https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places
Reference: For more marker icons designed by Google, you can refer here: What are the filenames of new colored Google maps markers?

Getting nearby places to the device current location using google places api on javascript

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>

Google Places API rankBy

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>

Show the location in Google Maps from a label

I have a label where includes a value of address. I want this address to be loaded in my google maps. The "prefered" solution is here Plases Search. But i don`t want this soloution. I dont want to search adreeses or stores or anything else. I just want my label value to be loaded in my google maps.
I would really appreciate any help! Thank you!
p.s. I have tried that solution but dont regonized some codes like var searchBox = new google.maps.places.SearchBox(search);The error says: "Uncaught ReferenceError: google is not defined"
Update:
<script>
var map;
var defaultLocation = { lat:37.977791, lng: 23.672878} ;
var infoWindow;
var marker;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: defaultLocation,
zoom: 15
});
infoWindow = new google.maps.InfoWindow({map: map});
// HTML5 Geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
defaultLocation = pos;
infoWindow.setPosition(pos);
infoWindow.setContent('<h4> You are here! </h4>');
map.setCenter(pos);
}, function() { //Geolocation service failed
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
//END HTML5 Geolocation.
document.getElementById('add-marker').addEventListener('click', addMarker);
document.getElementById('delete-marker').addEventListener('click', removeMarker);
}
//---->Here the problem!!!!!!!!!!!!!!!!
var search = document.getElementById('search');
var searchBox = new google.maps.places.SearchBox(search);
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
});
// Geolocation Function
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'<strong>Error:</strong> The Geolocation service failed.' :
'<strong>Error:</strong> Your browser doesn\'t support geolocation.');
}
// Add Marker
function addMarker() {
if (infoWindow){
infoWindow.close();
}
marker = new google.maps.Marker({
position: map.getCenter(),
draggable: true,
map: map
});
updateCurrentLatLng(marker.getPosition());
document.getElementById('add-marker').disabled = true;
marker.addListener('dragend', updateCurrentLatLng);
}
// Delete Marker
function removeMarker() {
marker.setMap(null);
document.getElementById('add-marker').disabled = false;
document.getElementById('latcoords').value =null;
document.getElementById('loncoords').value = null;
}
// Update the position of the marker in latitude and longitude
function updateCurrentLatLng(latLng){
document.getElementById('latcoords').value = marker.getPosition().lat();
document.getElementById('loncoords').value = marker.getPosition().lat();
}
</script>
You need to move the SearchBox initialization inside the initMap function. Currently it is running before the input with id="search" has been rendered in the DOM.
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: defaultLocation,
zoom: 15
});
infoWindow = new google.maps.InfoWindow({
map: map
});
// HTML5 Geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
defaultLocation = pos;
infoWindow.setPosition(pos);
infoWindow.setContent('<h4> You are here! </h4>');
map.setCenter(pos);
}, function() { //Geolocation service failed
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
//END HTML5 Geolocation.
document.getElementById('add-marker').addEventListener('click', addMarker);
document.getElementById('delete-marker').addEventListener('click', removeMarker);
var search = document.getElementById('search');
var searchBox = new google.maps.places.SearchBox(search);
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
});
} // end of initMap
proof of concept fiddle

Google Map API to find nearby restaurant around my place

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.

Categories

Resources