Need to add "directions to here" link in infowindow - javascript

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>

Related

Error with Script

I am getting an Add Marker is undefined when using this script but I can't seem to figure out the issue. Any suggestions to remedy this error is greatly appreciated:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<div id="map" style="width: 700px; height: 400px"></div>
<script type="text/javascript">
var latlng = new google.maps.LatLng(40.756, -73.986);
var options = {
center : latlng,
zoom : 1,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
// Creating the map
var map = new google.maps.Map(document.getElementById('map'), options);
var geocoder = new google.maps.Geocoder();
var marker= new google.maps.Marker(null);
function AddMarker(address)
{
geocoder.geocode( {'address' : address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
//map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker( {map : map,position : results[0].geometry.location });
var infowindow;
if (!infowindow)
{
infowindow = new google.maps.InfoWindow();
}
infowindow.setContent(address);
google.maps.event.addListener(marker, 'click', function()
{
infowindow.open(map,marker);
});
}
});
}
</script>
It looks like you have called the function "Add Marker" and not "AddMarker(target)"
you call infowindow just right the declaration of it.
It might be that you call AddMarker too early.
https://jsfiddle.net/c472zjqc/
var latlng = new google.maps.LatLng(40.756, -73.986);
var options = {
center: latlng,
zoom: 1,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Creating the map
var map = new google.maps.Map(document.getElementById('map'), options);
var geocoder = new google.maps.Geocoder();
var marker = new google.maps.Marker(null);
function AddMarker(address) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var infowindow;
if (!infowindow) {
infowindow = new google.maps.InfoWindow();
}
infowindow.setContent(address);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
});
}
AddMarker('Wichita, KS');
map.setZoom(3);
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<div id="map" style="width: 700px; height: 400px"></div>

How to remove information from info window (on a KmlLayer)

I am working with a Google Map API and I have imported a kml layer into my code.My problem is that I don't know how to remove the 'Unknown Point Feature' information from the info window. Any suggestions? here is a screenshot of what I am talking about:
This is my code for importing the kml file:
var AI_url = 'https://drive.google.com/uc?export=download&id=0B2KR4Lz3foYEeEtfR0laWWM0LVk'
var AI_options = {
preserveViewport: true,
map: map
};
var AI_layer = new google.maps.KmlLayer(AI_url, AI_options);
The info window content is coming from the KML file so you would have to remove it from there, provided you have access to the file from the location it's being served of course.
From the API:
https://developers.google.com/maps/tutorials/kml/
var kmlOptions = {
**suppressInfoWindows: true,**
preserveViewport: false,
map: map
};
One option would be to set the suppressInfoWindows option of the KmlLayer, then add your own click listener that just displays the "name":
var AI_url = 'https://drive.google.com/uc?export=download&id=0B2KR4Lz3foYEeEtfR0laWWM0LVk'
var AI_options = {
preserveViewport: true,
suppressInfoWindows: true,
map: map
};
var AI_layer = new google.maps.KmlLayer(AI_url, AI_options);
google.maps.event.addListener(AI_layer,'click',function(e) {
infoWindow.setOptions({
content:"<b>"+e.featureData.name+"</b>",
pixelOffset:e.pixelOffset,
position:e.latLng
});
infoWindow.open(map);
});
proof of concept code snippet:
var geocoder;
var map;
var infoWindow = new google.maps.InfoWindow();
function initialize() {
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var AI_url = 'https://drive.google.com/uc?export=download&id=0B2KR4Lz3foYEeEtfR0laWWM0LVk'
var AI_options = {
preserveViewport: true,
suppressInfoWindows: true,
map: map
};
var AI_layer = new google.maps.KmlLayer(AI_url, AI_options);
google.maps.event.addListener(AI_layer, 'click', function(e) {
infoWindow.setOptions({
content: "<b>" + e.featureData.name + "</b>",
pixelOffset: e.pixelOffset,
position: e.latLng
});
infoWindow.open(map);
});
codeAddress("Calgary, Canada");
}
google.maps.event.addDomListener(window, "load", initialize);
function codeAddress(address) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.fitBounds(results[0].geometry.viewport);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>

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

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);

Using Address Instead Of Longitude And Latitude With Google Maps API

I've heard that it is possible to submit an Address instead of Longitude and Latitude and this would be much more feasible for my system. The user has to input their address when creating their profile and their profile afterwards will then display a Google Maps of their house. I currently have the Google Maps API working perfectly with Longitude and Latitude:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="css.css" />
<title>Login Page</title>
<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: 100% }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=MYKEY&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.640143,1.28685),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(52.640143,1.28685),
map: map,
title: "Mark On Map"
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
Please could somebody assist me to alter my code so that it enables the Google Maps API to request an Address in its place because I want to read the Address of the user directly from mySQL database.
See this example, initializes the map to "San Diego, CA".
Uses the Google Maps Javascript API v3 Geocoder to translate the address into coordinates that can be displayed on the map.
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
var address ="San Diego, CA";
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
if (geocoder) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
var infowindow = new google.maps.InfoWindow(
{ content: '<b>'+address+'</b>',
size: new google.maps.Size(150,50)
});
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title:address
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%">
</body>
</html>
working code snippet:
var geocoder;
var map;
var address = "San Diego, CA";
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
if (geocoder) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
var infowindow = new google.maps.InfoWindow({
content: '<b>' + address + '</b>',
size: new google.maps.Size(150, 50)
});
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: address
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
}
<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" ></div>
You can parse the geolocation through the addresses.
Create an Array with jquery like this:
//follow this structure
var addressesArray = [
'Address Str.No, Postal Area/city'
]
//loop all the addresses and call a marker for each one
for (var x = 0; x < addressesArray.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addressesArray[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
//it will place marker based on the addresses, which they will be translated as geolocations.
var aMarker= new google.maps.Marker({
position: latlng,
map: map
});
});
}
Also please note that Google limit your results if you don't have a business account with them, and you my get an error if you use too many addresses.
Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway, Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can use to place markers or position the map.
Would this be what you are looking for: Contains sample code
https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingRequests
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == 'OK') {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
<body onload="initialize()">
<div id="map" style="width: 320px; height: 480px;"></div>
<div>
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Encode" onclick="codeAddress()">
</div>
</body>
Or refer to the documentation https://developers.google.com/maps/documentation/javascript/geocoding
Thought I'd share this code snippet that I've used before, this adds multiple addresses via Geocode and adds these addresses as Markers...
var addressesArray = [
'Address Str.No, Postal Area/city',
//follow this structure
]
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 12.7826,
lng: 105.0282
},
zoom: 6,
gestureHandling: 'cooperative'
});
var geocoder = new google.maps.Geocoder();
for (i = 0; i < addressArray.length; i++) {
var address = addressArray[i];
geocoder.geocode({
'address': address
}, function(results, status) {
if (status === 'OK') {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
center: {
lat: 12.7826,
lng: 105.0282
},
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}

Categories

Resources