Nearby places in google maps APIs - javascript

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

Related

Show nearest elements on google map

I am creating a project using google map. My project contains hospital address ( in longitude and latitude) to be stored in database. But I want to show nearest hospital from my current location. And I am unable to figure out how to do it. Please help me with best algorithm and with some code.
Following code is used just to display all hospital address in map now I want is how to show only 3 nearest hospital from my current positiom.
function initMap() {
var mapType = google.maps.MapTypeId.ROADMAP;
var animationType = google.maps.Animation.DROP;
var currentLocationAnimationType = google.maps.Animation.BOUNCE;
var mapElement = document.getElementById('map');
var nepalLocation = {
lat: 28.3949,
lng: 84.1240
};
var mapOptions = {
center: nepalLocation,
zoom: 7,
mapTypeId: mapType,
};
// actual map
map = new google.maps.Map(mapElement, mapOptions);
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var geocoder = geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p) {
var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: "My Location",
animation: currentLocationAnimationType
});
google.maps.event.addListener(marker, "click", function(e) {
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(marker.title);
infoWindow.open(map, marker);
});
});
} else {
alert('Geo Location feature is not supported in this browser.');
}
for (var i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var image = "img/iconHospital.png";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image,
title: data.district,
animation: animationType
});
}
}
google.maps.event.addDomListener(window, 'load', initMap);
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
</head>
<body>
<div id="map"></div>
</body>
</html>
See this example at. I adapted your code accordingly.
function initMap() {
var mapType = google.maps.MapTypeId.ROADMAP;
var animationType = google.maps.Animation.DROP;
var currentLocationAnimationType = google.maps.Animation.BOUNCE;
var mapElement = document.getElementById('map');
var nepalLocation = {
lat: 28.3949,
lng: 84.1240
};
var mapOptions = {
center: nepalLocation,
zoom: 7,
mapTypeId: mapType,
};
// actual map
map = new google.maps.Map(mapElement, mapOptions);
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var geocoder = geocoder = new google.maps.Geocoder();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p) {
var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: "My Location",
animation: currentLocationAnimationType
});
google.maps.event.addListener(marker, "click", function(e) {
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(marker.title);
infoWindow.open(map, marker);
});
});
} else {
alert('Geo Location feature is not supported in this browser.');
}
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: nepalLocation,
radius: 50000,
type: ['hospital']
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
if (i == 2) {
break;
}
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);
});
}
google.maps.event.addDomListener(window, 'load', initMap);
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>
<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>
</body>
</html>

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>

Geocoding and Animation.drop incompatible with timeout?

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>

Click action is not working for the below code in Google Maps

Can anyone please tell me what is wrong with this code? The map loads but a user's click action does not open up the info_window or re-center the map to the clicked point.
I want the address of a location to pop-up as an info_window whenever the user clicks on a map.
<!DOCTYPE html>
<html>
<head>
<title>Accessing arguments in UI events</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0px;
padding: 0px
}
#map-canvas {
height: 60%; width: 60%
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=geometry&key=MY_KEY&sensor=true">
</script>
<script type="text/javascript">
var geocoder;
var map;
var info_win;
var pos;
var marker;
function initialize()
{
google.maps.visualRefresh = true;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function(evt) {
pos = evt.latLng;
map.setCenter(pos);
geocoder.geocode({'location': pos}, function(results, status)
{
if(status == google.maps.GeocoderStatus.OK)
{
marker = new google.maps.Marker
({
map: map,
position: pos
});
info_win = new google.maps.InfoWindow
({
content: results[0].formatted_address,
});
info_win.open(map,marker);
}
else
{
alert("Could not load");
}
});
});
}
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
First problem: You are adding the click listener to the map outside of the initialize function, so it is being added before the map is initialized:
<script type="text/javascript">
var geocoder;
var map;
var info_win;
var pos;
var marker;
function initialize()
{
google.maps.visualRefresh = true;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function() {
pos = map.getPosition();
map.setCenter(pos);
geocoder.geocode({'location': pos}, function(results, status)
{
marker = new google.maps.Marker
({
map: map,
position: pos
});
info_win = new google.maps.InfoWindow
({
content: results[0].formatted_address,
});
infowindow.open(map,marker);
});
});
}
</script>
After that you will find that a google.maps.Map object does not have a getPosition method. It does have a getCenter method, but you probably want to use the latLng property of the click event instead.
google.maps.event.addListener(map, 'click', function(evt) {
pos = evt.latLng;
map.setCenter(pos);
And fix the code that opens the info_win to open the google.maps.InfoWindow that you created:
info_win = new google.maps.InfoWindow
({
content: results[0].formatted_address,
});
info_win.open(map,marker);

Need to add "directions to here" link in infowindow

I'm new to both Google Maps and Javascript but have to get this issue solved! I have an .html file with a google map of our client's location loaded into the map_canvas div. Through tutorials, I have been able to figure out how to write enough Javascript to get the map to function, have a custom marker and and infowindow that pops up when you click on it. The only part left is to have a link inside the infowindow that says "directions to here" and there's a text field that the user can type in their starting address. I'm seeing plenty of documentation to help me write my own code on the Google Developer's site but I am not advanced enough to do this. Can anyone help me figure out how to do this? Here is my Javascript:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize()
{
var latlng = new google.maps.LatLng(33.929011, -84.361);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(33.929011, -84.361),
map: map,
title: 'Atlanta/Sandy Springs',
clickable: true,
icon: 'images/mapmarker.png'
});
var infowindow = new google.maps.InfoWindow({
content: 'client address'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
</script>
There are several pieces I added. First, you need a better HTML form inside the infowindow, since I only put in the basic parts and it won't respond when you press Enter.
Next, I added a geocoder because the directions Service won't take "human readable" addresses, only latLng coordinates. The geocoder converts the two. Finally, the directions Service and Display are added. The directions text goes into a div (directionsPanel).
See the working fiddle or use this code:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html, body {
margin: 0;
padding: 0;
height: 100%
}
#map_canvas {
margin: 0;
padding: 0;
width: 50%;
height: 100%
}
#directionsPanel {
position: absolute;
top: 0px;
right: 0px;
width: 50%
}
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var directionsService;
var directionsDisplay;
function initialize() {
var latlng = new google.maps.LatLng(33.929011, -84.361);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(33.929011, -84.361),
map: map,
title: 'Atlanta/Sandy Springs',
clickable: true
});
var infowindow = new google.maps.InfoWindow({
content: "Your address: <input id='clientAddress' type='text'>"+
"<input type='button' onClick=getDir() value='Go!'>"
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
geocoder = new google.maps.Geocoder();
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: false
});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}
function getDir() {
geocoder.geocode({
'address': document.getElementById('clientAddress').value
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var origin = results[0].geometry.location;
var destination = new google.maps.LatLng(33.929011, -84.361);
var request = {
origin: origin,
destination: destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
} else {
document.getElementById('clientAddress').value =
"Directions cannot be computed at this time.";
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
<div id="directionsPanel"></div>
</body>
</html>

Categories

Resources