Google Maps V3: Draw German State Polygons? - google-maps

I need to draw colored polygons over certain German states. What's the best way (or easiest, fastest, any really...) to do this? Do I need to somehow get all the outlines as lat/lon points and draw a polygon based on those? Or is there a better way?

You want to do something like this?
http://www.geocodezip.com/geoxml3_test/v3_FusionTables_query_sidebarF_local.html?country=Germany
It uses publicly available data in FusionTables, the Natural Earth Data set.
encrypted ID:
https://www.google.com/fusiontables/DataSource?docid=19lLpgsKdJRHL2O4fNmJ406ri9JtpIIk8a-AchA
numeric ID:
https://www.google.com/fusiontables/DataSource?dsrcid=420419
You can style them (color them) as you like.
code snippet:
// globals
var map = null;
var infoWindow = null;
var geoXml = null;
var geoXmlDoc = null;
var myLatLng = null;
var myOptions = null;
var mapCenter = null;
var geocodeTheCountry = true;
var gpolygons = [];
// Fusion Table data ID
var FT_TableID = "19lLpgsKdJRHL2O4fNmJ406ri9JtpIIk8a-AchA"; // 420419;
var CountryName = "Germany";
google.load('visualization', '1', {
'packages': ['corechart', 'table', 'geomap']
});
function createSidebar() {
// set the query using the parameters
var FT_Query2 = "SELECT 'name_0', 'name_1', 'kml_4326' FROM " + FT_TableID + " WHERE name_0 = '" + CountryName + "' ORDER by 'name_1'";
var queryText = encodeURIComponent(FT_Query2);
// alert("createSidebar query="+FT_Query2);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(getData);
}
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(createSidebar);
var FTresponse = null;
myLatLng = new google.maps.LatLng(37.422104808, -122.0838851);
// these set the initial center, zoom and maptype for the map
// if it is not specified in the query string
var lat = 37.422104808;
var lng = -122.0838851;
var zoom = 18;
var maptype = google.maps.MapTypeId.ROADMAP;
if (!isNaN(lat) && !isNaN(lng)) {
myLatLng = new google.maps.LatLng(lat, lng);
}
infoWindow = new google.maps.InfoWindow();
//define callback function, this is called when the results are returned
function getData(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
FTresponse = response;
//for more information on the response object, see the documentation
//http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
fusiontabledata = "<table><tr>";
fusiontabledata += "<th>" + response.getDataTable().getColumnLabel(1) + "</th>";
// }
fusiontabledata += "</tr><tr>";
for (i = 0; i < numRows; i++) {
fusiontabledata += "<td><a href='javascript:myFTclick(" + i + ")'>" + response.getDataTable().getValue(i, 1) + "</a></td>";
// }
fusiontabledata += "</tr><tr>";
}
fusiontabledata += "</table>";
//display the results on the page
document.getElementById('sidebar').innerHTML = fusiontabledata;
}
function infoWindowContent(name, description) {
content = '<div class="FT_infowindow"><h3>' + name +
'</h3><div>' + description + '</div></div>';
return content;
}
function myFTclick(row) {
var description = FTresponse.getDataTable().getValue(row, 0);
var name = FTresponse.getDataTable().getValue(row, 1);
if (!gpolygons[row]) {
var kml = FTresponse.getDataTable().getValue(row, 2);
// create a geoXml3 parser for the click handlers
var geoXml = new geoXML3.parser({
map: map,
zoom: false,
infoWindow: infoWindow,
singleInfoWindow: true
});
geoXml.parseKmlString("<Placemark>" + kml + "</Placemark>");
geoXml.docs[0].gpolygons[0].setMap(null);
gpolygons[row] = geoXml.docs[0].gpolygons[0].bounds.getCenter();
}
var position = gpolygons[row];
if (!infoWindow) infoWindow = new google.maps.InfoWindow({});
infoWindow.setOptions({
content: infoWindowContent(name, description),
pixelOffset: new google.maps.Size(0, 2),
position: position
});
infoWindow.open(map);
}
function initialize() {
myOptions = {
zoom: zoom,
center: myLatLng,
mapTypeId: maptype
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var geocoder = new google.maps.Geocoder();
if (geocoder && geocodeTheCountry) {
geocoder.geocode({
'address': CountryName + " Country"
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
map.fitBounds(results[0].geometry.viewport);
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
var FT_Query = "SELECT 'kml_4326' FROM " + FT_TableID + " WHERE 'name_0' = '" + CountryName + "';";
var FT_Options = {
suppressInfoWindows: true,
query: {
from: FT_TableID,
select: 'kml_4326',
where: "'name_0' = '" + CountryName + "';"
},
styles: [{
polygonOptions: {
fillColor: "#FF0000",
fillOpacity: 0.35
}
}]
};
layer = new google.maps.FusionTablesLayer(FT_Options);
layer.setMap(map);
google.maps.event.addListener(layer, "click", function(event) {
infoWindow.close();
infoWindow.setContent(infoWindowContent(event.row.name_1.value, event.row.name_0.value));
infoWindow.setPosition(event.latLng);
infoWindow.open(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas {
width: 300px;
height: 100%
}
.infowindow * {
font-size: 90%;
margin: 0
}
<script src="https://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>
<script src="http://www.google.com/jsapi"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<table style="width:100%; height:100%;">
<tr style="width:100%; height:90%;">
<td style="width:60%; height:100%;">
<div id="map_canvas"></div>
</td>
<td>
<div id="sidebar" style="width:300px;height:400px; overflow:auto"></div>
</td>
</tr>
</table>

Also, you could take a look at the Google GeoChart API, which is not that feature-rich but pretty easy to use. Try the following code in the API playground:
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['Province', 'Popularity'],
['Bremen', 100],
['Niedersachsen', 900],
['Saksen', 700],
['Saarland', 300],
['Bayern', 400]
]);
var options = {
region: 'DE',
displayMode: 'regions',
colorAxis: {colors: ['green', 'blue']},
resolution:'provinces'
};
var geochart = new google.visualization.GeoChart(
document.getElementById('visualization'));
geochart.draw(data, options, {width: 556, height: 347});
}
​

Related

How to get a list of strings from FusionTablesLayer and associate it with the map

I have a google map built using FusionTablesLayer
How to get a list of strings from this FusionTablesLayer and associate it with the map. To click on an item from the list, a baloon was opened on the map.
Here is an example of the map http://air-in.ru/ajax/chat/test.php
This is an example of how a map should look.
<body>
<style type="text/css">
html, body, #googft-mapCanvas {
height: 100% !important;
margin: 0;
padding: 0;
width: 100% !important;
}
</style>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=AIzaSyBxMTfLhegh_rO8w0-vRP_oKdaJOvhOUUI"></script>
<script type="text/javascript">
function initialize() {
var isMobile = (navigator.userAgent.toLowerCase().indexOf('android') > -1) ||
(navigator.userAgent.match(/(iPod|iPhone|iPad|BlackBerry|Windows Phone|iemobile)/));
if (isMobile) {
var viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute('content', 'initial-scale=1.0, user-scalable=no');
}
var mapDiv = document.getElementById('googft-mapCanvas');
mapDiv.style.width = isMobile ? '100%' : '500px';
mapDiv.style.height = isMobile ? '100%' : '300px';
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(56.32085914650647, 62.40977352913535),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('googft-legend-open'));
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('googft-legend'));
layer = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "col0",
from: "1XlnmbK0m0s4rHdadG_hkmZP-dSr2ruBzQxnMK4Uv",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
if (isMobile) {
var legend = document.getElementById('googft-legend');
var legendOpenButton = document.getElementById('googft-legend-open');
var legendCloseButton = document.getElementById('googft-legend-close');
legend.style.display = 'none';
legendOpenButton.style.display = 'block';
legendCloseButton.style.display = 'block';
legendOpenButton.onclick = function() {
legend.style.display = 'block';
legendOpenButton.style.display = 'none';
}
legendCloseButton.onclick = function() {
legend.style.display = 'none';
legendOpenButton.style.display = 'block';
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="googft-mapCanvas"></div>
</body>
You are looking for a "sidebar". The FustionTablesLayer doesn't allow direct access to the FusionTable data, but you can use the visualization API to query the table and display information in the sidebar, then like that information to the map.
From my example at http://www.geocodezip.com/v3_FusionTables_AfricaMap_kml_sidebar.html
code snippet:
google.load('visualization', '1', {
'packages': ['corechart', 'table', 'geomap']
});
function createSidebar() {
//set the query using the parameter
var queryText = encodeURIComponent("https://www.google.com/fusiontables/gvizdata?tq=SELECT * FROM 564705");
var query = new google.visualization.Query(queryText);
queryText = encodeURIComponent("SELECT 'description', 'name', 'Citizens', 'Country', 'Latitude', 'Longitude' FROM 564705");
query = new google.visualization.Query('https://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(getData);
}
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(createSidebar);
var FTresponse = null;
//define callback function, this is called when the results are returned
function getData(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
FTresponse = response;
//for more information on the response object, see the documentation
//http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
//concatenate the results into a string, you can build a table here
fusiontabledata = "<table><tr>";
fusiontabledata += "<th>" + response.getDataTable().getColumnLabel(1) + "</th>";
fusiontabledata += "</tr><tr>";
for (i = 0; i < numRows; i++) {
fusiontabledata += "<td><a href='javascript:myFTclick(" + i + ")'>" + response.getDataTable().getValue(i, 1) + "</a></td>";
fusiontabledata += "</tr><tr>";
}
fusiontabledata += "</table>"
//display the results on the page
document.getElementById('sidebar').innerHTML = fusiontabledata;
}
function myFTclick(row) {
var description = FTresponse.getDataTable().getValue(row, 0);
var name = FTresponse.getDataTable().getValue(row, 1);
var lat = FTresponse.getDataTable().getValue(row, 4);
var lng = FTresponse.getDataTable().getValue(row, 5);
var position = new google.maps.LatLng(lat, lng);
// Set up and create the infowindow
if (!infoWindow) infoWindow = new google.maps.InfoWindow({});
infoWindow.setOptions({
content: '<div class="FT_infowindow"><h3>' + name +
'</h3><div>' + description + '</div></div>',
pixelOffset: new google.maps.Size(0, 2),
position: position
});
infoWindow.open(map);
}
var map = null;
var infoWindow = null;
function initialize() {
var africa = new google.maps.LatLng(1.56, 16.07);
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: africa,
zoom: 3,
mapTypeId: 'hybrid'
});
layer = new google.maps.FusionTablesLayer(564705, {
suppressInfoWindows: true
});
layer.setMap(map);
google.maps.event.addListener(layer, "click", function(event) {
infoWindow.close();
infoWindow.setContent(event.infoWindowHtml);
infoWindow.setPosition(event.latLng);
infoWindow.open(map);
});
infoWindow = new google.maps.InfoWindow();
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
background-color: white;
}
.infowindow * {
font-size: 90%;
margin: 0
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://maps.google.com/maps/api/js"></script>
<table style="width:100%;height:100%">
<tr style="width:100%;height:100%">
<td style="width:100%;height:100%">
<div id="map_canvas"></div>
</td>
<td>
<div id="sidebar" style="width:260px;height:100%; overflow:auto"></div>
</td>
</tr>
</table>

How to pass location and radius in google map API?

My goal is to get list of zip codes by passing parameter of location and radius of particular limit.
I got only the location, but I couldn't get the radius of certain zipcode.
https://maps.googleapis.com/maps/api/elevation/json?locations=7034&key=YOUR_API_KEY
How can I get the list of zipcode in certain radius ?
Please guide me to solve this issue
You need a database that contains data about the zipcodes. Here is an example that uses a FusionTable containing US zip codes:
http://www.geocodezip.com/geoxml3_test/v3_FusionTables_zipcodeInRadius.html
code snippet:
google.load('visualization', '1', {
'packages': ['corechart', 'table', 'geomap']
});
var map;
var labels = [];
var layer;
var tableid = "1VFp4XJEdnR769R2CFRghlmDpUd15dQArpwzcBBs"; //1499916;
var circle;
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: new google.maps.LatLng(37.23032838760389, -118.65234375),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
layer = new google.maps.FusionTablesLayer({
query: {
from: tableid,
select: "geometry"
}
});
// layer.setQuery("SELECT 'geometry' FROM " + tableid);
layer.setMap(map);
codeAddress();
}
function codeAddress() {
var address = document.getElementById("address").value;
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
});
if (results[0].geometry.viewport)
map.fitBounds(results[0].geometry.viewport);
var latLng = results[0].geometry.location;
var radius = parseFloat(document.getElementById('radius').value) * 1609.34;
if (isNaN(radius)) radius = 5 * 1609.34; // default to 5 miles
displayZips(results[0].geometry.location, radius);
if (circle && circle.setMap) {
circle.setMap(null);
}
circle = new google.maps.Circle({
center: latLng,
radius: radius,
map: map
});
layer.setQuery({
select: 'geometry',
from: tableid,
where: "ST_INTERSECTS(geometry, CIRCLE(LATLNG(" + latLng.toUrlValue(6) + ")," + radius.toFixed(2) + "))"
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function displayZips(latLng, radius) {
var queryStr = "SELECT geometry, ZIP, latitude, longitude FROM " + tableid + " WHERE ST_INTERSECTS(geometry, CIRCLE(LATLNG(" + latLng.toUrlValue(6) + ")," + radius.toFixed(2) + "))";
var queryText = encodeURIComponent(queryStr);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(displayZipText);
}
var infowindow = new google.maps.InfoWindow();
function displayZipText(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
if (map.getZoom() < 11) return;
FTresponse = response;
//for more information on the response object, see the documentation
//http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
var zipsList = "";
for (i = 0; i < numRows; i++) {
var zip = response.getDataTable().getValue(i, 1);
var zipStr = zip.toString()
while (zipStr.length < 5) {
zipStr = '0' + zipStr;
}
zipsList += zipStr + " ";
var point = new google.maps.LatLng(
parseFloat(response.getDataTable().getValue(i, 2)),
parseFloat(response.getDataTable().getValue(i, 3)));
}
document.getElementById('zips').innerHTML = "zipcodes in radius=" + zipsList;
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
width: 100%;
height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="http://www.google.com/jsapi"></script>
<form>
<span class="style51"><span class="style49">Show</span>:</span>
<label>Address:</label><input id="address" type="text" value="07646" /><label>Radius:</label><input id="radius" type="text" value="0.5" />
<input id="geocode" type="button" onclick="codeAddress();" value="Geocode" />
</form>
<div id="zips"></div>
<div id="map_canvas"></div>

Using geo location to set google maps centre

I am aiming to have a map that centre's on a user's current location with markers pulled from a mysql database displayed. I can make my map display a certain lat or lng when specified but I am having trouble taking the user's current location and using this to modify the map's centre.
Any help would be appreciated!
:)
<!DOCTYPE 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>PHP/MySQL & Google Maps Example</title>
<script src="markerclusterer.js" type="text/javascript"></script>
<script src="https://maps.googleapis.com/maps/api/js? key="
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
function showLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("Latitude : " + latitude + " Longitude: " + longitude);
}
function errorHandler(err) {
if(err.code == 1) {
alert("Error: Access is denied!");
}
else if( err.code == 2) {
alert("Error: Position is unavailable!");
}
}
function getLocation(){
if(navigator.geolocation){
// timeout at 60000 milliseconds (60 seconds)
var options = {timeout:60000};
navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options);
}
else{
alert("Sorry, browser does not support geolocation!");
}
}
var customIcons = {
restaurant: {
icon: 'http://orthodontistsearch.com.au/data/documents/Icon.png',
},
bar: {
icon: 'http://orthodontistsearch.com.au/data/documents/Icon.png',
}
};
function load() {
var cluster = [];
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng('latitude' , 'longitude'),
zoom: 4,
mapTypeId: 'roadmap'
});
var infowindow = new google.maps.InfoWindow();
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var type = markers[i].getAttribute("type");
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var phone = markers[i].getAttribute("phone");
var url = markers[i].getAttribute("url");
var html = name + "<br>" + "Address: " + address + "<br>" + "Phone Number: " + phone + "<br>" + " Website: " + url + "<br>" ;
infowindow.setContent(html);
infowindow.open(map, marker, html);
}
})(marker, i));
cluster.push(marker);
}
var mc = new MarkerClusterer(map,cluster);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
</head>
<body onload="load()">
<style type="text/css">
div#map { margin: 0 auto 0 auto; }
</style>
<div id="map" style="width: 80%; height: 500px"></div>
</body>
i m uploading demo code which i have used in my system for map display in center. Hope this will help you.
Logic
$result_count = $query_count->result(); //Count row
$count = $result_count[0]->total / 2;
if($count % 2 == 0){
$cal = $count - 0.5;
$query_latlng = $this->db->query("SELECT latitude, longitude FROM 'table_name' WHERE id = '$cal' ");
$result_latlng = $query_latlng->result();
}
else{
$cal = $count;
$query_latlng = $this->db->query("SELECT latitude, longitude FROM 'table_name' WHERE id = '$cal' ");
$result_latlng = $query_latlng->result();
}
Google Map
var cluster = [];
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(<?php echo $result_latlng[0]->latitude; ?>,<?php echo $result_latlng[0]->longitude; ?>),
zoom: 4,
mapTypeId: 'roadmap'
});

Google Maps API Directions - Move directions link to sidebar

Currently when you click on a marker, a clickable get directions link comes up along with title and address. I would also like the get directions link to appear on the sidebar as well.
<!DOCTYPE html>
<html>
<head>
<title>Google Maps JavaScript API v3 Example: Map Simple</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map_canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<style type='text/css'>
.text
{
width:300px;
height:600px;
background-color:white;
overflow:scroll;
overflow-x: hidden;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>
<script type="text/javascript">
// Store Name[0],Address[1],Coordinates[2],Icon[3]
var locations = [
["John Doe", "145 Rock Ridge Road, Chester, NY ", "41.314926,-74.270134", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
["Jim Smith", "12 Williams Rd, Montvale, NJ ", "41.041599,-74.019554", "http://maps.google.com/mapfiles/ms/icons/green.png"],
["John Jones", "689 Fern St Township of Washington, NJ ", "40.997704,-74.050598", "http://maps.google.com/mapfiles/ms/icons/yellow.png"],
];
// alert(locations.length);
var geocoder = null;
var map = null;
var customerMarker = null;
var gmarkers = [];
var closest = [];
var directionsDisplay = new google.maps.DirectionsRenderer();;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map'),
{
zoom: 9,
center: new google.maps.LatLng(52.6699927, -0.7274620),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var bounds = new google.maps.LatLngBounds();
document.getElementById('info').innerHTML = "found "+locations.length+" locations<br>";
for (i = 0; i < locations.length; i++) {
var coordStr = locations[i][2];
var coords = coordStr.split(",");
var pt = new google.maps.LatLng(parseFloat(coords[0]),parseFloat(coords[1]));
bounds.extend(pt);
marker = new google.maps.Marker({
position: pt,
map: map,
icon: locations[i][3],
address: locations[i][1],
title: locations[i][0],
**html: locations[i][0]+"<br>"+locations[i][1]+"<br><br><a href='javascript:getDirections(customerMarker.getPosition(),""+locations[i][1]+"");'>Get Directions</a>"**
});
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) { return function()
{ infowindow.setContent(marker.html);
infowindow.open(map, marker);
}
})
(marker, i));
}
map.fitBounds(bounds);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
if (customerMarker) customerMarker.setMap(null);
customerMarker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
closest = findClosestN(results[0].geometry.location,12);
// get driving distance
closest = closest.splice(0,12);
calculateDistances(results[0].geometry.location, closest,12);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function findClosestN(pt,numberOfResults) {
var closest = [];
document.getElementById('info').innerHTML += "processing "+gmarkers.length+"<br>";
for (var i=0; i<gmarkers.length;i++) {
gmarkers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt,gmarkers[i].getPosition());
document.getElementById('info').innerHTML += "process "+i+":"+gmarkers[i].getPosition().toUrlValue(6)+":"+gmarkers[i].distance.toFixed(2)+"<br>";
gmarkers[i].setMap(null);
closest.push(gmarkers[i]);
closest.sort(sortByDist);
}
return closest;
}
function sortByDist(a,b) {
return (a.distance- b.distance)
}
function calculateDistances(pt,closest,numberOfResults) {
var service = new google.maps.DistanceMatrixService();
var request = {
origins: [pt],
destinations: [],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
};
for (var i=0; i < closest.length; i++) {
request.destinations.push(closest[i].getPosition());
}
service.getDistanceMatrix(request, function (response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('side_bar');
outputDiv.innerHTML = '';
var results = response.rows[0].elements;
// save title and address in record for sorting
for (var i = 0; i < closest.length; i++) {
results[i].title = closest[i].title;
results[i].address = closest[i].address;
results[i].idx_closestMark = i;
}
results.sort(sortByDistDM);
for (var i = 0;
((i < numberOfResults) && (i < closest.length)); i++) {
closest[i].setMap(map);
**outputDiv.innerHTML += "<a href='javascript:google.maps.event.trigger(closest[" + results[i].idx_closestMark + "],\"click\");'>" + results[i].title + '</a><br>' + results[i].address + "<br>" + results[i].distance.text + ' approximately ' + results[i].duration.text + "<br><a href='javascript:getDirections(customerMarker.getPosition(),""+locations[i][1]+"");'>Get Directions</a><br><hr>"**
}
}
});
}
function getDirections(origin, destination) {
var request = {
origin:origin,
destination:destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setMap(map);
directionsDisplay.setDirections(response);
directionsDisplay.setPanel(document.getElementById('side_bar'));
}
});
}
function sortByDistDM(a, b) {
return (a.distance.value - b.distance.value)
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<table border="0"><tr><td>
<div id="map" style="height: 600px; width:800px;"></div>
</td><td>
<div id="side_bar" class = 'text'> </div>
</td></tr></table>
<input id="address" type="text" value="Palo Alto, CA"></input>
<input type="button" value="Search" onclick="codeAddress();"></input>
<div id="info"></div>
</body>
</html>
I tried to move from here:
html: locations[i][0]+"<br>"+locations[i][1]+"<br><br><a href='javascript:getDirections(customerMarker.getPosition(),""+locations[i][1]+"");'>Get Directions</a>"
to here:
outputDiv.innerHTML += "<a href='javascript:google.maps.event.trigger(closest[" + results[i].idx_closestMark + "],\"click\");'>" + results[i].title + '</a><br>' + results[i].address + "<br>" + results[i].distance.text + ' approximately ' + results[i].duration.text + "<br><a href='javascript:getDirections(customerMarker.getPosition(),""+locations[i][1]+"");'>Get Directions</a><br><hr>"
I'm now able to have the get directions link appear in the sidebar, however the directions don't match up to correct title and address like they do from the marker. Anyone know how to fix this?
You need to use the "sorted" version of the address, not the version in the input.
// save title and address in record for sorting
for (var i = 0; i < closest.length; i++) {
results[i].title = closest[i].title;
results[i].address = closest[i].address;
results[i].idx_closestMark = i;
}
results.sort(sortByDistDM);
// use the stored values in the output to the sidebar
for (var i = 0;
((i < numberOfResults) && (i < closest.length)); i++) {
closest[i].setMap(map);
outputDiv.innerHTML += "<a href='javascript:google.maps.event.trigger(closest[" + results[i].idx_closestMark + "],\"click\");'>" + results[i].title + '</a><br>' + results[i].address + "<br>" + results[i].distance.text + ' approximately ' + results[i].duration.text + "<br><a href='javascript:getDirections(customerMarker.getPosition(),"" + results[i].address + "");'>Get Directions</a><br><hr>"
}
sort function:
function sortByDistDM(a, b) {
return (a.distance.value - b.distance.value)
}
proof of concept fiddle
code snippet:
var locations = [
["John Doe", "145 Rock Ridge Road, Chester, NY ", "41.314926,-74.270134", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
["Jim Smith", "12 Williams Rd, Montvale, NJ ", "41.041599,-74.019554", "http://maps.google.com/mapfiles/ms/icons/green.png"],
["John Jones", "689 Fern St Township of Washington, NJ ", "40.997704,-74.050598", "http://maps.google.com/mapfiles/ms/icons/yellow.png"],
];
// alert(locations.length);
var geocoder = null;
var map = null;
var customerMarker = null;
var gmarkers = [];
var closest = [];
var directionsDisplay = new google.maps.DirectionsRenderer();;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
// alert("init");
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 9,
center: new google.maps.LatLng(52.6699927, -0.7274620),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var bounds = new google.maps.LatLngBounds();
document.getElementById('info').innerHTML = "found " + locations.length + " locations<br>";
for (i = 0; i < locations.length; i++) {
var coordStr = locations[i][2];
var coords = coordStr.split(",");
var pt = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
bounds.extend(pt);
marker = new google.maps.Marker({
position: pt,
map: map,
icon: locations[i][3],
address: locations[i][1],
title: locations[i][0],
html: locations[i][0] + "<br>" + locations[i][1] + "<br><br><a href='javascript:getDirections(customerMarker.getPosition(),"" + locations[i][1] + "");'>Get Directions</a>"
});
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(marker.html);
infowindow.open(map, marker);
}
})
(marker, i));
}
map.fitBounds(bounds);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
if (customerMarker) customerMarker.setMap(null);
customerMarker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
closest = findClosestN(results[0].geometry.location, 12);
// get driving distance
closest = closest.splice(0, 12);
calculateDistances(results[0].geometry.location, closest, 12);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function findClosestN(pt, numberOfResults) {
var closest = [];
document.getElementById('info').innerHTML += "processing " + gmarkers.length + "<br>";
for (var i = 0; i < gmarkers.length; i++) {
gmarkers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt, gmarkers[i].getPosition());
document.getElementById('info').innerHTML += "process " + i + ":" + gmarkers[i].getPosition().toUrlValue(6) + ":" + gmarkers[i].distance.toFixed(2) + "<br>";
gmarkers[i].setMap(null);
closest.push(gmarkers[i]);
closest.sort(sortByDist);
}
return closest;
}
function sortByDist(a, b) {
return (a.distance - b.distance)
}
function calculateDistances(pt, closest, numberOfResults) {
var service = new google.maps.DistanceMatrixService();
var request = {
origins: [pt],
destinations: [],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
};
for (var i = 0; i < closest.length; i++) {
request.destinations.push(closest[i].getPosition());
}
service.getDistanceMatrix(request, function(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('side_bar');
outputDiv.innerHTML = '';
var results = response.rows[0].elements;
// save title and address in record for sorting
for (var i = 0; i < closest.length; i++) {
results[i].title = closest[i].title;
results[i].address = closest[i].address;
results[i].idx_closestMark = i;
}
results.sort(sortByDistDM);
for (var i = 0;
((i < numberOfResults) && (i < closest.length)); i++) {
closest[i].setMap(map);
outputDiv.innerHTML += "<a href='javascript:google.maps.event.trigger(closest[" + results[i].idx_closestMark + "],\"click\");'>" + results[i].title + '</a><br>' + results[i].address + "<br>" + results[i].distance.text + ' approximately ' + results[i].duration.text + "<br><a href='javascript:getDirections(customerMarker.getPosition(),"" + results[i].address + "");'>Get Directions</a><br><hr>"
}
}
});
}
function getDirections(origin, destination) {
var request = {
origin: origin,
destination: destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setMap(map);
directionsDisplay.setDirections(response);
directionsDisplay.setPanel(document.getElementById('side_bar'));
}
});
}
function sortByDistDM(a, b) {
return (a.distance.value - b.distance.value)
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
margin: 0;
padding: 0;
height: 100%;
}
table,tr,td {
height: 100%;
}
.text {
width: 300px;
height: 500px;
background-color: white;
overflow: scroll;
overflow-x: hidden;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<table border="0">
<tr>
<td>
<div id="map" style="height: 100%; width:400px;"></div>
</td>
<td>
<div id="side_bar" class='text'> </div>
</td>
</tr>
</table>
<input id="address" type="text" value="Paramus, NJ" />
<input type="button" value="Search" onclick="codeAddress();" />
<div id="info"></div>

Google Maps Api V3 Zoom links in infowindow not working

I am building a store locator using php sql and javascript. I've done this tutorial https://developers.google.com/maps/articles/phpsqlsearch_v3 and got it working. I am trying to implement zoom in/out links on the infoWindows, for when the user clicks a marker. Its not working, in FireFox I am getting no errors in the console. In Chrome I am getting Uncaught TypeError: Object # has no method 'setCenter'
Ive been searching the forums but have been unable to find a solution. Sorry I dont have a version online to look at, working locally. Below is the script I am using.
var map = null;
var markers = [];
var infoWindow;
var locationSelect;
//On page load Create a google map in #map
//Set default cordinates & Map style to roadmap
function load() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(43.907787,-79.359741),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
infoWindow = new google.maps.InfoWindow({
size: new google.maps.Size(150,50)
});
locationSelect = document.getElementById("locationSelect");
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
if (markerNum != "none") {
google.maps.event.trigger(markers[markerNum], 'click');
}
};
}
//Search for LAT/LNG of a place using its address using Google Maps Geocoder
function searchLocations() {
var address = document.getElementById("addressInput").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
searchLocationsNear(results[0].geometry.location);
} else {
alert(address + ' not found');
}
});
}
//Clears Prve location, in info box
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
locationSelect.innerHTML = "";
var option = document.createElement("option");
option.value = "none";
option.innerHTML = "See all results:";
locationSelect.appendChild(option);
}
//Look for locations near by and loop through all data getting lat & lng of each marker
function searchLocationsNear(center) {
clearLocations();
var radius = document.getElementById('radiusSelect').value;
var searchUrl = 'http://localhost:8888/starward/wp-content/themes/starward/map_request.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
downloadUrl(searchUrl, function(data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var zoom = 18;
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
createOption(name, distance, i);
createMarker(latlng, name, address,zoom);
bounds.extend(latlng);
}
map.fitBounds(bounds);
map.setZoom(11);
// map.setCenter(center);
locationSelect.style.visibility = "visible";
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
google.maps.event.trigger(markers[markerNum], 'click');
};
});
}
//Creates marker on the map
//Adds event for user when they click address info pops up
function createMarker(latlng, name, address, zoom) {
//var html = "<b>" + name + "</b> <br/>" + address
// add the zoom links
var html = "<b>" + name + "</b> <br/>" + address
html += '<br>Zoom To';
html += ' [+]';
html += ' [-]';
var marker = new google.maps.Marker({
position: latlng,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
marker.MyZoom = zoom;
markers.push(marker);
}
function createOption(name, distance, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name + "(" + distance.toFixed(1) + ")";
locationSelect.appendChild(option);
}
//Look up XML sheet to get data
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
It works for me in both IE and Firefox. Although to me the behavior makes more sense if I set the center for the "ZoomTo" link as well:
html += '<br>Zoom To';