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>
Related
i have to mark the head-office to branch office with poly-line, below code work only for branch office, not marked for head-office to branch-office.
ex:-
head-office may be -- Delhi,
branch office -- Chennai, Mumbai, Bangalore
my code working for branch office only, i would like show head-office to each branch office to marked with Poly-line
can anybody share good idea to solve...
code:-
$(function () {
start();
});
function start() {
var markers = [
{HOLat:13.089562900000,HOLng:80.290230500000,DeLat:12.990928000000, DeLng: 80.242616500000},
{HOLat:13.089562900000,HOLng:80.290230500000,DeLat:12.991269800000, DeLng: 80.242545000000},
{HOLat:13.089562900000,HOLng:80.290230500000,DeLat:12.991316800000, DeLng: 80.242520000000}
]
if (!isEmpty(markers)) {
var mapOptions = {
center: new google.maps.LatLng(markers[0].HOLat, markers[0].HOLng),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var start = '';
var points = [];
for (i = 0; i < markers.length; i++) {
img = "icons/" + (i+1) + ".png";
var data = markers[i];
myLatlng = new google.maps.LatLng(data.DeLat, data.DeLng);
points.push(new google.maps.LatLng(data.DeLat, data.DeLng));
var marker = new google.maps.Marker({
position: myLatlng,
icon: img,
map: map,
animation: google.maps.Animation.DROP,
title: 'MAP'
});
marker.addListener('click', toggleBounce);
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
var latlng = { lat: parseFloat(marker.position.lat()), lng: parseFloat(marker.position.lng()) };
var geocoder = new google.maps.Geocoder;
geocoder.geocode({ 'location': latlng }, function (results, status) {
if (status === 'OK') {
if (results[1]) {
infoWindow.setContent(data.DistName);
infoWindow.open(map, marker);
}
}
else {
infoWindow.setContent(data.DistName);
infoWindow.open(map, marker);
}
});
});
})(marker, data);
}
var polyOptions = {
path: points,
strokeColor: "#FF0000",
strokeOpacity: 1,
strokeWeight: 3
}
var it = new google.maps.Polyline(polyOptions);
it.setMap(map);
}
}
if this solved means very easy to build google map
google key from web.config:-
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=<%=ConfigurationManager.AppSettings["GoogleAPIKey"] %>"></script>
line map & Route Map:-
<script type="text/javascript">
//code by Ethiraj.G on 15.12.2018, ver = 1.01
$(function () {
start();
});
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function isEmpty(str) {
return typeof str == 'string' && !str.trim() || typeof str == 'undefined' || str === null || str == 0;
}
$(function () {
var h = $(window).height();
h = h - 100;
w = $(window).width();
});
/*
function start() {
var UserID = getUrlVars()['ID'];
var paramstr = '';
paramstr += "#EmpID$" + UserID;
paramstr += "~#Date$" + '<%= Session["Date"] %>';
paramstr += "~#UserID$" + '<%= Session["UserTypeID"] %>';
paramstr += "~#UserTypeID$" + '<%= Session["UserTypeID"] %>';
paramstr += "~#Type$" + 'V';
var markers = GetRowData_Tables("DBSP_Rpt_MDOSub_ActivityPlan", paramstr, "Sample.aspx/GetRowData_Tables");
if (!isEmpty(markers)) {
var mapOptions = {
center: new google.maps.LatLng(markers[0].Lat, markers[0].Lon),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var start = '';
var points = [];
for (i = 0; i < markers.length; i++) {
img = "icons/" + (i+1) + ".png";
var data = markers[i];
myLatlng = new google.maps.LatLng(data.Lat, data.Lon);
points.push(new google.maps.LatLng(data.Lat, data.Lon));
var marker = new google.maps.Marker({ position: myLatlng, icon: img, map: map, title: 'MAP' });
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
var latlng = { lat: parseFloat(marker.position.lat()), lng: parseFloat(marker.position.lng()) };
var geocoder = new google.maps.Geocoder;
geocoder.geocode({ 'location': latlng }, function (results, status) {
if (status === 'OK') {
if (results[1]) {
var dist = '';
//infoWindow.setContent('<b> Names :</b> ' + data.Names + '<br /><b> Emp Name :</b> ' + data.EmpName + '<br /><b> StartTime :</b> ' + data.StartTime + '<br /><b> End Time :</b> ' + data.EndTime + '<br /><b> StartDate :</b> ' + data.StartDate + '<br /><b> Location :</b> ' + results[1].formatted_address + '<br /><b> Dist Name :</b> ' + data.DistName + '<br />');
infoWindow.setContent( data.DistName );
infoWindow.open(map, marker);
}
}
else {
//infoWindow.setContent('<b> Names :</b> ' + data.Names + '<br /><b> Emp Name :</b> ' + data.EmpName + '<br /><b> StartTime :</b> ' + data.StartTime + '<br /><b> End Time :</b> ' + data.EndTime + '<br /><b> StartDate :</b> ' + data.StartDate + '<br /><b> Location :</b> ' + results[1].formatted_address + '<br /><b> Dist Name :</b> ' + data.DistName + '<br />');
infoWindow.setContent( data.DistName );
infoWindow.open(map, marker);
}
});
});
})(marker, data);
}
var polyOptions = { path: points, strokeColor: "#FF0000", strokeOpacity: 1, strokeWeight: 3 }
var it = new google.maps.Polyline(polyOptions);
it.setMap(map);
}
}
*/
function start() {
var UserID = getUrlVars()['ID'];
var paramstr = '';
paramstr += "#EmpID$" + UserID;
paramstr += "~#Date$" + '<%= Session["Date"] %>';
paramstr += "~#UserID$" + '<%= Session["UserTypeID"] %>';
paramstr += "~#UserTypeID$" + '<%= Session["UserTypeID"] %>';
paramstr += "~#Type$" + 'V';
//debugger
var markers = GetRowData_Tables("DBSP_Rpt_MDOSub_ActivityPlan", paramstr, "Sample.aspx/GetRowData_Tables");
if (!isEmpty(markers)) {
var directionsService = new google.maps.DirectionsService;
map = new google.maps.Map(document.getElementById("map_canvas"), { center: new google.maps.LatLng(markers[0].HOLat, markers[0].HOLng),
zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP });
var start1 = [], end1 = []; var img = '';
for (i = 0; i < markers.length; i++)
{
var data = markers[i];
var img= 'icons/' + (i+1) + ".png";
start1 = new google.maps.LatLng(markers[0].HOLat, markers[0].HOLng);
end1 = new google.maps.LatLng(data.Lat, data.Lon);
var directionsDisplay = new google.maps.DirectionsRenderer({ map: map, polylineOptions: { strokeColor: '#03a5ef' },
strokeOpacity: 5.0, strokeWeight: 50, suppressMarkers: true });
DisplayRoute(directionsService, directionsDisplay, start1, end1, map, data, img);
}
}
}
function DisplayRoute(directionsService, directionsDisplay, start1, end1, map, data, img) {
directionsService.route({ origin: start1, destination: end1, travelMode: 'DRIVING', optimizeWaypoints : true
}, function (response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
if(i == 0)
{
var img1 = "icons/" + "0.png";
var cs = '<div>' +data.Discription+'</div>';
createMarkerfarmer(legs[i].start_location, cs, img1);
}
var cs = '<div>' + data.DistName + '<br/><b> Distance: '+ response.routes[0].legs[0].distance.text +'</b></div>';
createMarkerfarmer(legs[i].end_location, cs, img);
}
}
});
}
function createMarkerfarmer(latlng, contentString, marker_icon) {
var marker = new google.maps.Marker({
position: latlng, map: map,
animation: google.maps.Animation.DROP,
icon: marker_icon, strokeColor: '#FF0000',
strokeOpacity: 0.8, strokeWeight: 1, fillOpacity: 0.8, clickable: true
});
var infoWindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
function Map_Date(date) {
var newDate = '';
if (date.length > 0) {
date = date.split('/');
newDate = date[2] + '/' + date[1] + '/' + date[0];
}
return newDate;
}
function GetRowData_Tables(procName, paramstr, url) {
var rowData;
$.ajax({
url: url,
type: "POST",
dataType: "json",
async: false,
data: "{procedureName: '" + procName + "',paramstr: '" + paramstr + "'}",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (!isEmpty(data.d))
rowData = $.parseJSON(data.d);
else
rowData = '[]';
},
error: function (error) { }
});
return rowData;
}
//code by Ethiraj.G on 15.12.2018, ver = 1.01
</script>
commented lines are line map rest of that Road Map working fine
I am using JavaScript in HTML page to display GPS locations with markers and all these GPS locations are connected
I am trying to implement a map/direction based application using Google maps V3 API. So far I have been able to display the map and show directions for two locations selected. the first one is my current location , the second one is the location of costumer (his/her information exist in my database). All the markers are being displayed in the output properly.
To get directions to a location specified by coordinates, make it a google.maps.LatLng object. To get that from your data in the select, save the coordinates as a string in the value, then parse out the latitude and longitude to create the LatLng object.
save the coordinates in the option value:
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
addOption(selectBox, data[i]['CodeClient'], data[i].Latitude + "," + data[i].Longitude);
}
parse those coordinates and create a google.maps.LatLng object in the directions request:
function calculateRoute() {
var start = document.getElementById('start').value;
var destination = document.getElementById('destination').value;
console.log("selected option value=" + destination);
var destPt = destination.split(",");
var destination = new google.maps.LatLng(destPt[0], destPt[1]);
if (start == '') {
start = center;
}
// ....
proof of concept fiddle
code snippet:
var map;
var directionsService;
var directionsDisplay;
var geocoder;
var infowindow;
function init() {
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
var mapOptions = {
zoom: 6,
center: center = new google.maps.LatLng(32, -6),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions_panel'));
// Detect user location
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var userLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
geocoder.geocode({
'latLng': userLocation
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById('start').value = results[0].formatted_address
}
});
}, function() {
alert('Geolocation is supported, but it failed');
});
}
makeRequest('https://gist.githubusercontent.com/abdelhakimsalama/358669eda44d8d221bf58c629402c40b/raw/eca59a21899fe19b1f556ff033a33dff2a6bdd0c/get_data_google_api', function(data) {
var data = JSON.parse(data.responseText);
var selectBox = document.getElementById('destination');
for (var i = 0; i < data.length; i++) {
displayLocation(data[i]);
addOption(selectBox, data[i]['CodeClient'], data[i].Latitude + "," + data[i].Longitude);
}
});
}
function addOption(selectBox, text, value) {
var option = document.createElement("OPTION");
option.text = text;
option.value = value;
selectBox.options.add(option);
}
function calculateRoute() {
var start = document.getElementById('start').value;
var destination = document.getElementById('destination').value;
console.log("selected option value=" + destination);
var destPt = destination.split(",");
var destination = new google.maps.LatLng(destPt[0], destPt[1]);
if (start == '') {
start = center;
}
var request = {
origin: start,
destination: destination,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
console.log("origin:" + start);
console.log("dest:" + destination.toUrlValue(12));
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
} else {
request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
}
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
function displayLocation(rythmstu_innotec) {
var content = '<div class="infoWindow"><strong> Code Client : ' + rythmstu_innotec.CodeClient + '</strong>' +
'<br />Latitude : ' + rythmstu_innotec.Latitude +
'<br />Longitude : ' + rythmstu_innotec.Longitude +
'<br />Route : ' + rythmstu_innotec.Route +
'<br />Secteur : ' + rythmstu_innotec.Secteur +
'<br />Agence : ' + rythmstu_innotec.Agence +
'<br />prenom de Client : ' + rythmstu_innotec.PrenomClient +
'<br />Num Adresse : ' + rythmstu_innotec.NumAdresse +
'<br />GeoAdresse : ' + rythmstu_innotec.GeoAdresse +
'<br />Téléphone : ' + rythmstu_innotec.Tel +
'<br />Whatsapp : ' + rythmstu_innotec.Whatsapp +
'<br />Nbr Frigos : ' + rythmstu_innotec.NbrFrigo +
'<br />Ouverture Matin : ' + rythmstu_innotec.OpenAm +
'<br />Fermeture Matin : ' + rythmstu_innotec.CloseAm +
'<br />Ouverture après-midi : ' + rythmstu_innotec.OpenPm +
'<br />Fermeture Après-midi : ' + rythmstu_innotec.ClosePm + '</div>';
if (parseInt(rythmstu_innotec.Latitude) == 0) {
geocoder.geocode({
'GeoAdresse': rythmstu_innotec.GeoAdresse
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.rythmstu_innotec,
title: rythmstu_innotec.name
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
});
} else {
var position = new google.maps.LatLng(parseFloat(rythmstu_innotec.Latitude), parseFloat(rythmstu_innotec.Longitude));
var marker = new google.maps.Marker({
map: map,
position: position,
title: rythmstu_innotec.name
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
}
}
body {
font: normal 14px Verdana;
}
h1 {
font-size: 24px;
}
h2 {
font-size: 18px;
}
#sidebar {
float: right;
width: 30%;
}
#main {
padding-right: 15px;
}
.infoWindow {
width: 220px;
}
<title>MAP itinéraire </title>
<meta charset="utf-8">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<body onload="init();">
<form id="services">
Location: <input type="text" id="start" value="Midar" /> Destination:
<select id="destination" onchange="calculateRoute();"></select>
<input type="button" value="afficher la direction" onclick="calculateRoute();" />
</form>
<section id="sidebar">
<div id="directions_panel"></div>
</section>
<section id="main">
<div id="map_canvas" style="width: 70%; height: 750px;"></div>
</section>
</body>
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>
Is it possible to plot multiple markers as well show routes between these and origin? For example: I have one origin and four different destinations. I want the routes to be shown between the origin and the destinations, so that it is A to B, A to C, A to D, A to E. Can this be done? I have only seen the option to display the route between two points or to calculate distance between multiple. I want to be able to calculate the distance as well as showing the route on the map.
So far this is what my code looks like:
$("#submit").click(function() {
var values = $("#street").val();
var geocoder = new google.maps.Geocoder();
var address = values;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
}
service = new google.maps.DistanceMatrixService();
var origin = new google.maps.LatLng(latitude, longitude);
var destination = new google.maps.LatLng(48.856614, 2.352222);
var destinationb = new google.maps.LatLng(41.385064, 2.173403);
var destinationc = new google.maps.LatLng(44.584910, 5.133122);
var destinationd = new google.maps.LatLng(45.365187, 0.647394);
var destinationIcon = 'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2278%22%20height%3D%2238%22%20viewBox%3D%220%200%2038%2038%22%3E%3Cpath%20fill%3D%22%23333333%22%20stroke%3D%22%23ccc%22%20stroke-width%3D%22.5%22%20d%3D%22M34.305%2016.234c0%208.83-15.148%2019.158-15.148%2019.158S3.507%2025.065%203.507%2016.1c0-8.505%206.894-14.304%2015.4-14.304%208.504%200%2015.398%205.933%2015.398%2014.438z%22%2F%3E%3Ctext%20transform%3D%22translate(19%2018.5)%22%20fill%3D%22%23fff%22%20style%3D%22font-family%3A%20Arial%2C%20sans-serif%3Bfont-weight%3Abold%3Btext-align%3Acenter%3B%22%20font-size%3D%2212%22%20text-anchor%3D%22middle%22%3E' + "" + '%3C%2Ftext%3E%3C%2Fsvg%3E';
var originIcon = 'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2238%22%20height%3D%2238%22%20viewBox%3D%220%200%2038%2038%22%3E%3Cpath%20fill%3D%22%23808880%22%20stroke%3D%22%23ccc%22%20stroke-width%3D%22.5%22%20d%3D%22M34.305%2016.234c0%208.83-15.148%2019.158-15.148%2019.158S3.507%2025.065%203.507%2016.1c0-8.505%206.894-14.304%2015.4-14.304%208.504%200%2015.398%205.933%2015.398%2014.438z%22%2F%3E%3Ctext%20transform%3D%22translate%2819%2018.5%29%22%20fill%3D%22%23fff%22%20style%3D%22font-family%3A%20Arial%2C%20sans-serif%3Bfont-weight%3Abold%3Btext-align%3Acenter%3B%22%20font-size%3D%2212%22%20text-anchor%3D%22middle%22%3E' + "" + '%3C%2Ftext%3E%3C%2Fsvg%3E';
var infowindow = new google.maps.InfoWindow();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination, destinationb, destinationc, destinationd],
travelMode: google.maps.TravelMode.DRIVING,
avoidHighways: false,
avoidTolls: false
},
callback
);
function callback(response, status) {
if(status=="OK") {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var bounds = new google.maps.LatLngBounds;
var outputDiv = document.getElementById('output');
var showGeocodedAddressOnMap = function(distance, asDestination) {
var icon = asDestination ? destinationIcon : originIcon;
return function(results, status) {
if (status === 'OK') {
map.fitBounds(bounds.extend(results[0].geometry.location));
var markersArray = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
});
google.maps.event.addListener(markersArray, 'click', function (evt) {
infowindow.setContent('<strong>Avstånd:</strong> ' + distance);
infowindow.open(map, this);
});
} else {
alert('Geocode was not successful due to: ' + status);
}
};
};
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
geocoder.geocode({'address': originList[i]},
showGeocodedAddressOnMap(results[i].distance.text, false));
for (var j = 0; j < results.length; j++) {
geocoder.geocode({'address': destinationList[j]}, showGeocodedAddressOnMap(results[j].distance.text, true));
outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] +
': ' + results[j].distance.text + '<br>';
}
}
} else {
alert("Error: " + status);
}
}
var map = new google.maps.Map(document.getElementById('map'), {
showTooltip: true,
showInfoWindow: true
});
});
});
</script>
<div id="output"></div>
<p></p>
<div id="map"></div>
To display the routes, call the directions service. Modified function from the example in the documentation:
function calculateAndDisplayRoute(start, end, map) {
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
suppressMarkers: true,
preserveViewport: true
});
directionsService.route({
origin: start,
destination: end,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
calculateAndDisplayRoute(origin, destination, map);
calculateAndDisplayRoute(origin, destinationb, map);
calculateAndDisplayRoute(origin, destinationc, map);
calculateAndDisplayRoute(origin, destinationd, map);
proof of concept fiddle
code snippet:
function calculateAndDisplayRoute(start, end, map) {
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
suppressMarkers: true,
preserveViewport: true
});
directionsService.route({
origin: start,
destination: end,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
var map = new google.maps.Map(document.getElementById('map'), {
showTooltip: true,
showInfoWindow: true
});
var values = $("#street").val();
var geocoder = new google.maps.Geocoder();
var address = values;
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
}
service = new google.maps.DistanceMatrixService();
var origin = new google.maps.LatLng(latitude, longitude);
var destination = new google.maps.LatLng(48.856614, 2.352222);
var destinationb = new google.maps.LatLng(41.385064, 2.173403);
var destinationc = new google.maps.LatLng(44.584910, 5.133122);
var destinationd = new google.maps.LatLng(45.365187, 0.647394);
var destinationIcon = 'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2278%22%20height%3D%2238%22%20viewBox%3D%220%200%2038%2038%22%3E%3Cpath%20fill%3D%22%23333333%22%20stroke%3D%22%23ccc%22%20stroke-width%3D%22.5%22%20d%3D%22M34.305%2016.234c0%208.83-15.148%2019.158-15.148%2019.158S3.507%2025.065%203.507%2016.1c0-8.505%206.894-14.304%2015.4-14.304%208.504%200%2015.398%205.933%2015.398%2014.438z%22%2F%3E%3Ctext%20transform%3D%22translate(19%2018.5)%22%20fill%3D%22%23fff%22%20style%3D%22font-family%3A%20Arial%2C%20sans-serif%3Bfont-weight%3Abold%3Btext-align%3Acenter%3B%22%20font-size%3D%2212%22%20text-anchor%3D%22middle%22%3E' + "" + '%3C%2Ftext%3E%3C%2Fsvg%3E';
var originIcon = 'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2238%22%20height%3D%2238%22%20viewBox%3D%220%200%2038%2038%22%3E%3Cpath%20fill%3D%22%23808880%22%20stroke%3D%22%23ccc%22%20stroke-width%3D%22.5%22%20d%3D%22M34.305%2016.234c0%208.83-15.148%2019.158-15.148%2019.158S3.507%2025.065%203.507%2016.1c0-8.505%206.894-14.304%2015.4-14.304%208.504%200%2015.398%205.933%2015.398%2014.438z%22%2F%3E%3Ctext%20transform%3D%22translate%2819%2018.5%29%22%20fill%3D%22%23fff%22%20style%3D%22font-family%3A%20Arial%2C%20sans-serif%3Bfont-weight%3Abold%3Btext-align%3Acenter%3B%22%20font-size%3D%2212%22%20text-anchor%3D%22middle%22%3E' + "" + '%3C%2Ftext%3E%3C%2Fsvg%3E';
var infowindow = new google.maps.InfoWindow();
calculateAndDisplayRoute(origin, destination, map);
calculateAndDisplayRoute(origin, destinationb, map);
calculateAndDisplayRoute(origin, destinationc, map);
calculateAndDisplayRoute(origin, destinationd, map);
service.getDistanceMatrix({
origins: [origin],
destinations: [destination, destinationb, destinationc, destinationd],
travelMode: google.maps.TravelMode.DRIVING,
avoidHighways: false,
avoidTolls: false
},
callback
);
function callback(response, status) {
if (status == "OK") {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
var bounds = new google.maps.LatLngBounds;
var outputDiv = document.getElementById('output');
var showGeocodedAddressOnMap = function(distance, asDestination) {
var icon = asDestination ? destinationIcon : originIcon;
return function(results, status) {
if (status === 'OK') {
map.fitBounds(bounds.extend(results[0].geometry.location));
var markersArray = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
});
google.maps.event.addListener(markersArray, 'click', function(evt) {
if (asDestination) {
infowindow.setContent('<strong>Avstånd:</strong> ' + distance);
} else {
infowindow.setContent('<strong>Origin</strong> ');
}
infowindow.open(map, this);
});
} else {
alert('Geocode was not successful due to: ' + status);
}
};
};
for (var i = 0; i < originList.length; i++) {
var results = response.rows[i].elements;
var text;
if (results[i].status != "OK") {
text = results[i].status;
} else {
results[i].distance.text;
}
geocoder.geocode({
'address': originList[i]
},
showGeocodedAddressOnMap(text, false));
for (var j = 0; j < results.length; j++) {
console.log("j=" + j + " destinationList[" + j + "]=" + destinationList[j] + " results[" + j + "]=" + results[j]);
geocoder.geocode({
'address': destinationList[j]
}, showGeocodedAddressOnMap(results[j].distance.text, true));
outputDiv.innerHTML += originList[i] + ' to ' + destinationList[j] +
': ' + results[j].distance.text + '<br>';
}
}
} else {
alert("Error: " + status);
}
}
});
html,
body,
#map {
height: 90%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="output"></div>
<input id="street" value="Orléans, France" />
<input id="submit" type="button" value="click" />
<p></p>
<div id="map"></div>
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});
}