Google Maps API V3 - Label Fusion Tables polygons by employing InfoBox - json

I'm trying inside Google Maps API V3 to Label Fusion Tables polygons by employing InfoBox,
for this I use example from http://www.geocodezip.com/geoxml3_test/v3_FusionTables_zipcode_map_whiteBg.html,
but code (as shown below) do not display labels:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Label Fusion Tables polygons by employing InfoBox</title>
<style>
#map_canvas { width: 610px; height: 400px; }
.style1 {font-size: 14px}
</style>
<!--Load the AJAX API-->
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://www.google-analytics.com/urchin.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://www.google.com/fusiontables/gvizdata?tq="></script>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart', 'table', 'geomap']});
var map;
var labels = [];
var layer;
var tableid = 1499916;
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(tableid);
layer.setQuery("SELECT 'geometry' FROM " + tableid);
layer.setMap(map);
codeAddress();
google.maps.event.addListener(map, "bounds_changed", function() {
displayZips();
});
google.maps.event.addListener(map, "zoom_changed", function() {
if (map.getZoom() < 11) {
for (var i=0; i<labels.length; i++) {
labels[i].setMap(null);
}
}
});
}
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);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function displayZips() {
//set the query using the current bounds
var queryStr = "SELECT geometry, ZIP, latitude, longitude FROM "+ tableid + " WHERE ST_INTERSECTS(geometry, RECTANGLE(LATLNG"+map.getBounds().getSouthWest()+",LATLNG"+map.getBounds().getNorthEast()+"))";
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;
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
for(i = 0; i < numRows; i++) {
var zip = response.getDataTable().getValue(i, 1);
var zipStr = zip.toString()
while (zipStr.length < 5) { zipStr = '0' + zipStr; }
var point = new google.maps.LatLng(
parseFloat(response.getDataTable().getValue(i, 2)),
parseFloat(response.getDataTable().getValue(i, 3)));
labels.push(new InfoBox({
content: zipStr
,boxStyle: {
border: "1px solid black"
,textAlign: "center"
,backgroundColor:"white"
,fontSize: "8pt"
,width: "50px"
}
,disableAutoPan: true
,pixelOffset: new google.maps.Size(-25, 0)
,position: point
,closeBoxURL: ""
,isHidden: false
,enableEventPropagation: true
}));
labels[labels.length-1].open(map);
}
}
</script>
<body onload="initialize();">
<form>
<span class="style1">Show:</span>
<input id="address" type="text" value="07646" ></input>
<input id="geocode" type="button" onclick="codeAddress();" value="Geocode"></input>
<div id="map_canvas"></div>
</body>
</html>
Does anyone have any suggestions?
Best regards,
Darko

I get a javascript error "google is undefined".
Doesn't look like you are including the Google Maps Javascript API v3 in the right place (it is needed for geoxml3 and infobox). If I fix that I see zip code labels on the polygons.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<!--Load the AJAX API-->
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"></script>
Not sure what this is for:
<script type="text/javascript" src="http://www.google.com/fusiontables/gvizdata?tq="></script>

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>

I want to open maps infowindow from a link on the table

im currenty undataking a project which includes a google map API!im loading markers on the map using mysql from my database. now what am trying to accomplish is something like this i have seen before http://www.tanesco.co.tz/index.php?option=com_wrapper&view=wrapper&Itemid=155
I want to create a link on the displayed table which when clicked it opens up an info window on the map....I completely have no idea where to start
This is my map code
<?php include("connect.php");
?>
<!DOCTYPE html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="stylesheet.css" type="text/css" rel="stylesheet" media="screen" />
<title>AzamTv Customer Database</title>
<style type="text/css">
<!--
.style2 {color: #999999}
.style3 {color: #666666}
.style4 {color: #FF0000}
.style5 {color: #3366FF}
-->
</style>
<script src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script language="javascript" type="text/javascript">
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);
}
//Get element by ID where the function return tand get the latitude and longitude
//do not embed any thing before authorized permition to google.
function load() {
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng( -6.801859, 39.282503),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl("mapxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var licence_number = markers[i].getAttribute("Licence_number");
var phone = markers[i].getAttribute("phone");
var business_image = markers[i].getAttribute("business_image");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
//Creating image
var image_src= "<div><img width='100' height='100' src=' "+ business_image +"' /></div>";
var html = "<b>" +"<h4>Business Name:</h4>"+ name + "</b> <br/><br/>"+"<h4>Address:</h4>" + address + "</b> <br/><br/>"+"<h4>Licence Type:</h4>" + licence_number + "</b> <br/><br/>" + "<h4>Phone:</h4>" + phone + "</b> <br/><br/>"+"<h4>Image:</h4>" + image_src + "</br> Zoom out Zoom in" ;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
//If u wanna change the markers by adding custom ones of ur own add here
var customIcons = {
TIN: {
icon: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png'
},
VAT: {
icon: 'http://maps.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png'
}
};
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
// Pan map center to marker position
map.panTo(marker.getPosition());
var c= map.getZoom()+3;
var maxZoom=map.mapTypes[map.getMapTypeId()].maxZoom;
if(c<=maxZoom){
map.setZoom(c+3);
}
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function doNothing() {}
function zoomout() {
var d = map.getZoom();
if(d>0){
map.setZoom(d-1);
}
// e = map.getCenter();
// map.setZoom(d - 1);
// map.setCenter(e.Longitude, e.Latitude);
// should be: map.setCenter(e.lat(), e.lng());
}
function zoomin() {
var x = map.getZoom();
var maxZoom=map.mapTypes[map.getMapTypeId()].maxZoom;
if(x<maxZoom){
map.setZoom(x+1);
}
// y = map.getCenter();
// map.setZoom(x + 1);
// map.setCenter(y.Longitude, y.Latitude);
// should be: map.setCenter(y.lat(), y.lng());
}
</script>
<script language="javascript" type="text/javascript">
//Script For The Search
function cleartxt()
{
formsearch.searched1.value="";
}
function settxt()
{
if(formsearch.searched1.value=="")
{
formsearch.searched1.value="Search Customer";
}
}
</script>
</head>
<body onLoad="load()">
<div id="map" style="width: 100%; height: 80%"></div>
</body>
</html>
Thank you all in advance
You create markers like
var marker = new google.maps.Marker({
position: myLatlng,
title:"Your title"
});
create links which on click trigger
infowindow.open(map,marker);
thats all i guess.
EDIT: You could identify which marker needs to be shown by href-parameter

Google Maps Over Query Limit but have Long and Lat

I have the coordinates (Long & Lat) that I'm having PHP insert all of them but I don't know how to change the javascript to correct the over query limit error.
here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="markerclusterer.js"></script>
<script type="text/javascript">
var map;
//marker clusterer
var mc;
var mcOptions = {gridSize: 20, maxZoom: 17};
//global infowindow
var infowindow = new google.maps.InfoWindow();
//geocoder
var geocoder = new google.maps.Geocoder();
var address = new Array(<?php echo(substr($point_str, 0, -2));?>);
var content = new Array(<?php echo(substr($marker_str, 0, -2));?>);
//min and max limits for multiplier, for random numbers
//keep the range pretty small, so markers are kept close by
var min = .999999;
var max = 1.000001;
function createMarker(latlng,text) {
///get array of markers currently in cluster
var allMarkers = mc.getMarkers();
//final position for marker, could be updated if another marker already exists in same position
var finalLatLng = latlng;
//check to see if any of the existing markers match the latlng of the new marker
if (allMarkers.length != 0) {
for (i=0; i < allMarkers.length; i++) {
var existingMarker = allMarkers[i];
var pos = existingMarker.getPosition();
//if a marker already exists in the same position as this marker
if (latlng.equals(pos)) {
//update the position of the coincident marker by applying a small multipler to its coordinates
var newLat = latlng.lat() * (Math.random() * (max - min) + min);
var newLng = latlng.lng() * (Math.random() * (max - min) + min);
finalLatLng = new google.maps.LatLng(newLat,newLng);
}
}
}
var marker = new google.maps.Marker({
position: finalLatLng
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.close();
infowindow.setContent(text);
infowindow.open(map,marker);
});
return marker;
}
function geocodeAddress(address,i) {
geocoder.geocode( {'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
var marker = createMarker(results[0].geometry.location,content[i]); mc.addMarker(marker);
}
else
{
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function initialize(){
var options = {
zoom: 4,
center: new google.maps.LatLng(39.8282,-98.5795),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), options);
//marker cluster
mc = new MarkerClusterer(map, [], mcOptions);
for (i=0; i<address.length; i++) {
geocodeAddress(address[i],i);
}
}
</script>
<style>
html, body, #map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body onload='initialize()'>
<div id="map"></div>
</body>
</html>
This is the HTML OUTPUT:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="markerclusterer.js"></script>
<script type="text/javascript">
var map;
//marker clusterer
var mc;
var mcOptions = {gridSize: 20, maxZoom: 17};
//global infowindow
var infowindow = new google.maps.InfoWindow();
//geocoder
var geocoder = new google.maps.Geocoder();
var address = new Array("42.0619,-72.2136",
"28.06,-81.9561",
"30.3375,-81.7686",
"30.3375,-81.7686",
"41.7684,-88.1366",
"28.06,-81.9561",
"40.086,-82.486",
"40.6278,-79.0896",
"39.0197,-84.5914",
"41.8119,-87.6873",
"28.06,-81.9561",
"42.8698,-85.9697",
"42.8358,-85.6644",
"41.0309,-92.4098",
"39.1024,-94.5986",
"33.6115,-84.3745",
"34.84,-115.967",
"33.0807,-81.9868",
"41.7369,-73.7411",
"41.9214,-87.8924");
var content = new Array("UnitNo1",
"UnitNo2",
"UnitNo3",
"UnitNo4",
"UnitNo5",
"UnitNo6",
"UnitNo7",
"UnitNo8",
"UnitNo9",
"UnitNo10",
"UnitNo11",
"UnitNo12",
"UnitNo13",
"UnitNo14",
"UnitNo15",
"UnitNo16",
"UnitNo17",
"UnitNo18",
"UnitNo19",
"UnitNo20");
//min and max limits for multiplier, for random numbers
//keep the range pretty small, so markers are kept close by
var min = .999999;
var max = 1.000001;
function createMarker(latlng,text) {
///get array of markers currently in cluster
var allMarkers = mc.getMarkers();
//final position for marker, could be updated if another marker already exists in same position
var finalLatLng = latlng;
//check to see if any of the existing markers match the latlng of the new marker
if (allMarkers.length != 0) {
for (i=0; i < allMarkers.length; i++) {
var existingMarker = allMarkers[i];
var pos = existingMarker.getPosition();
//if a marker already exists in the same position as this marker
if (latlng.equals(pos)) {
//update the position of the coincident marker by applying a small multipler to its coordinates
var newLat = latlng.lat() * (Math.random() * (max - min) + min);
var newLng = latlng.lng() * (Math.random() * (max - min) + min);
finalLatLng = new google.maps.LatLng(newLat,newLng);
}
}
}
var marker = new google.maps.Marker({
position: finalLatLng
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.close();
infowindow.setContent(text);
infowindow.open(map,marker);
});
return marker;
}
function geocodeAddress(address,i) {
geocoder.geocode( {'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
var marker = createMarker(results[0].geometry.location,content[i]); mc.addMarker(marker);
}
else
{
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function initialize(){
var options = {
zoom: 4,
center: new google.maps.LatLng(39.8282,-98.5795),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), options);
//marker cluster
mc = new MarkerClusterer(map, [], mcOptions);
for (i=0; i<address.length; i++) {
geocodeAddress(address[i],i);
}
}
</script>
<style>
html, body, #map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body onload='initialize()'>
<div id="map"></div>
</body>
</html>
Thank you!
If you have the latitude and longitude for the points, don't use the geocoder.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/src/markerclusterer.js"></script>
<script type="text/javascript">
var map;
//marker clusterer
var mc;
var mcOptions = {gridSize: 20, maxZoom: 17};
//global infowindow
var infowindow = new google.maps.InfoWindow();
//geocoder
var geocoder = new google.maps.Geocoder();
var address = new Array("42.0619,-72.2136",
"28.06,-81.9561",
"30.3375,-81.7686",
"30.3375,-81.7686",
"41.7684,-88.1366",
"28.06,-81.9561",
"40.086,-82.486",
"40.6278,-79.0896",
"39.0197,-84.5914",
"41.8119,-87.6873",
"28.06,-81.9561",
"42.8698,-85.9697",
"42.8358,-85.6644",
"41.0309,-92.4098",
"39.1024,-94.5986",
"33.6115,-84.3745",
"34.84,-115.967",
"33.0807,-81.9868",
"41.7369,-73.7411",
"41.9214,-87.8924");
var content = new Array("UnitNo1",
"UnitNo2",
"UnitNo3",
"UnitNo4",
"UnitNo5",
"UnitNo6",
"UnitNo7",
"UnitNo8",
"UnitNo9",
"UnitNo10",
"UnitNo11",
"UnitNo12",
"UnitNo13",
"UnitNo14",
"UnitNo15",
"UnitNo16",
"UnitNo17",
"UnitNo18",
"UnitNo19",
"UnitNo20");
//min and max limits for multiplier, for random numbers
//keep the range pretty small, so markers are kept close by
var min = .999999;
var max = 1.000001;
function createMarker(latlng,text) {
var marker = new google.maps.Marker({
position: latlng,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.close();
infowindow.setContent(text);
infowindow.open(map,marker);
});
return marker;
}
function initialize(){
var options = {
zoom: 4,
center: new google.maps.LatLng(39.8282,-98.5795),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), options);
var gmarkers = [];
for (i=0; i<address.length; i++) {
var ptStr = address[i];
var coords = ptStr.split(",");
var latlng = new google.maps.LatLng(parseFloat(coords[0]),parseFloat(coords[1]));
gmarkers.push(createMarker(latlng,content[i]));
}
//marker cluster
mc = new MarkerClusterer(map, gmarkers, mcOptions);
}
</script>
<style>
html, body, #map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body onload='initialize()'>
<div id="map"></div>
</body>
</html>
working example

google-maps-api-3 - Geolocate my position and save it into a MySQL database

I have been developing the practice of URL: https://developers.google.com/maps/articles/phpsqlinfo_v3 and it works, but in another example I need that the same window HTML form appears when i click the marker that shows on the map when i use the code to geolocate my position and to save that information into a MySQL database. I'm using the code below but the HTML form window does´nt appear to save the geolocation data.
This is the code used in the webpage: phpsqlinfo_add.html (similar name of the URL Sample: https://developers.google.com/maps/articles/phpsqlinfo_v3) The other complementary webpages: phpsqlinfo_addrow.php and phpsqlinfo_dbinfo.php are similar to the example.
CODE OF: phpsqlinfo_add.html
<!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>:: DEMO ::</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function detectBrowser() {
var useragent = navigator.userAgent;
var mapdiv = document.getElementById("map_canvas");
if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1 ) {
mapdiv.style.width = '100%';
mapdiv.style.height = '100%';
} else {
mapdiv.style.width = '600px';
mapdiv.style.height = '800px';
}
}
function init() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var marcador = new google.maps.Marker();
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 16,
center: pos,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
marcador.setPosition(pos);
marcador.setMap(map)
}, function() {
alert("Su navegador debe soportar geolocalizacion");
});
}
}
google.maps.event.addDomListener(window, 'load', init);
var map = new google.maps.Map(document.getElementById("map_canvas"), options);
var html = "<table>" +
"<tr><td>Nombre:</td> <td><input type='text' id='name' value='Juan Gomez' readonly='readonly' /> </td> </tr>" +
"<tr><td>Direccion:</td> <td><input type='text' id='address'/></td> </tr>" +
"<tr><td>Tipo:</td> <td><select id='type'>" +
"<option value='Opcion 1' SELECTED>Opcion 1</option>" +
"<option value='Opcion 2'>Opcion 2</option>" +
"<option value='Opcion 3'>Opcion 3</option>" +
"</select> </td></tr>" +
"<tr><td></td><td><input type='button' value='Registrar' onclick='saveData()'/></td></tr>";
infowindow = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(map, "click", function(event) {
marker = new google.maps.Marker({
position: event.latLng,
map: map_canvas
});
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
});
function saveData() {
var name = escape(document.getElementById("name").value);
var address = escape(document.getElementById("address").value);
var type = document.getElementById("type").value;
var latlng = marker.getPosition();
var url = "phpsqlinfo_addrow.php?name=" + name + "&address=" + address +
"&type=" + type + "&lat=" + latlng.lat() + "&lng=" + latlng.lng();
downloadUrl(url, function(data, responseCode) {
if (responseCode == 200 && data.length <= 1) {
infowindow.close();
document.getElementById("message").innerHTML = "Ubicacion Registrada.";
}
});
}
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.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
</head>
<body style="margin:0px; padding:0px;" onLoad="initialize()">
<div id="map_canvas" style="width: 500px; height: 300px"></div>
<div id="message"></div>
</body>
</html>
The code adding the onclick event listeners & creating the infowindow was never being activated, plus you are referencing the map_canvas div instead of your map. Try this (see // * my comments * for changes):
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function detectBrowser() {
var useragent = navigator.userAgent;
var mapdiv = document.getElementById("map_canvas");
if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1 ) {
mapdiv.style.width = '100%';
mapdiv.style.height = '100%';
} else {
mapdiv.style.width = '600px';
mapdiv.style.height = '800px';
}
}
function init() {
// * adjusted geolocation code for testing *
var pos = new google.maps.LatLng(51.511,0.275);
var marcador = new google.maps.Marker();
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 16,
center: pos,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
marcador.setPosition(pos);
marcador.setMap(map)
// * infowindow code wasn't being activated, moved inside init() function *
var html = "<table>" +
"<tr><td>Nombre:</td> <td><input type='text' id='name' value='Juan Gomez' readonly='readonly' /> </td> </tr>" +
"<tr><td>Direccion:</td> <td><input type='text' id='address'/></td> </tr>" +
"<tr><td>Tipo:</td> <td><select id='type'>" +
"<option value='Opcion 1' SELECTED>Opcion 1</option>" +
"<option value='Opcion 2'>Opcion 2</option>" +
"<option value='Opcion 3'>Opcion 3</option>" +
"</select> </td></tr>" +
"<tr><td></td><td><input type='button' value='Registrar' onclick='saveData()'/></td></tr>";
infowindow = new google.maps.InfoWindow({
content: html
});
// * changed map: map_canvas to map: map *
google.maps.event.addListener(map, "click", function(event) {
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
});
google.maps.event.addListener(map, "click", function(event) {
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
});
}
google.maps.event.addDomListener(window, 'load', init);
// * don't need to create map again *
// var map = new google.maps.Map(document.getElementById("map_canvas"), options);
// * rest of code should be fine... *
Also be careful with the <body onLoad="initialize()"> and google.maps.event.addDomListener(window, 'load', init); If this is not a mistake and initialize() does something different then it would be better to combine init() and initialize().

Getting country code from Google Maps and HTML 5 GeoLocation

I am trying to use HTML 5 GeoLocation to get a longitude and latitude and then use Google Maps API to get the country code of that longitude/latitude. Can anybody tell me where I am going wrong in my code, I currently get the Javascript error 'this.lat is not a function' in main.js :
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script src="http://maps.google.com/maps?file=api&v=2&key=drnhdhddfhgfghfg" type="text/javascript"></script>
<script type="text/javascript">
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var latlng = new google.maps.LatLng(lat, lng);
$.post('http://maps.googleapis.com/maps/api/geocode/json', { latlng: latlng, sensor: false }, function (results) {
alert(results);
});
});
}
else {
alert("Geolocation services are not supported by your browser.");
}
</script>
</head>
<body>
</body>
</html>
Try this:
<html>
<head>
<script src="http://maps.google.com/maps/api/js?sensor=true" type="text/javascript"></script>
<script type="text/javascript">
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
alert(results[7].formatted_address);
}
} else {
alert("Geocoder failed due to: " + status);
}
});
});
} else {
alert("Geolocation services are not supported by your browser.");
}
</script>
</head>
<body>
</body>
</html>