Google Map InfoWindow Content Binding - javascript

I'm new with Google map. I'm having problem in rebinding the data in my infowindow.
When I close the window using the "x" button in the upper right of the infowindow,
then open it again, all of the updated contents of the infowindow will load again to
its initial state instead of the latest update? What I want is that when I close the
infowindow, the infowindow must have the latest data.
<!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 type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="D:\Program Files\xampp\xampp\htdocs\googletest\progressBar.js"></script>
<script type="text/javascript">
//<![CDATA[
var infoWindow=new Array();
var htmlPrevious=new Array();
var html;
var marker=new Array();
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(7.11425, 124.83758),
zoom: 11,
mapTypeId: 'roadmap'
});
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
html = new Array(markers.length);
infowindow = new Array(markers.length);
for (var i = 0; i < markers.length; i++) {
infoWindow[i] = new google.maps.InfoWindow;
var sender = markers[i].getAttribute("sender");
var update = markers[i].getAttribute("update_time");
var name = markers[i].getAttribute("name");
var humidity = markers[i].getAttribute("humidity");
var temperature = markers[i].getAttribute("temperature");
var rain = markers[i].getAttribute("rain");
var wind_dir = markers[i].getAttribute("wind_dir");
var wind_speed = markers[i].getAttribute("wind_speed");
var image = markers[i].getAttribute("image");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
html[i] = "<div style='display:block;' width='600' height='300' overflow='hidden'><img style='display:block;' src='"+image+" ' width='300' height='184' /> <br/><b>" + name + "</b> <br/>Sender: " + sender + "<br/>Time: " + update + "<br/> Humidity: " + humidity + "<br/>Temperature: " + temperature + "<br/>Rain: " + rain + "<br/>Wind Direction: " + wind_dir + "<br/>Wind Speed: " + wind_speed + "<div>";
htmlPrevious[i]=html[i];
marker[i] = new google.maps.Marker({
map: map,
position: point,
title: name
});
bindInfoWindow(marker[i], map, infoWindow[i], html[i]);
}//end for loop
});//downloadurl
setInterval("refreshMarker()",1000);
}
function refreshMarker(){
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 sender = markers[i].getAttribute("sender");
var update = markers[i].getAttribute("update_time");
var name = markers[i].getAttribute("name");
var humidity = markers[i].getAttribute("humidity");
var temperature = markers[i].getAttribute("temperature");
var rain = markers[i].getAttribute("rain");
var wind_dir = markers[i].getAttribute("wind_dir");
var wind_speed = markers[i].getAttribute("wind_speed");
var image = markers[i].getAttribute("image");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
html[i] = "<div style='display:block;' width='600' height='300' overflow='hidden'><img style='display:block;' src='"+image+" ' width='300' height='184' /> <br/><b>" + name + "</b> <br/>Sender: " + sender + "<br/>Time: " + update + "<br/> Humidity: " + humidity + "<br/>Temperature: " + temperature + "<br/>Rain: " + rain + "<br/>Wind Direction: " + wind_dir + "<br/>Wind Speed: " + wind_speed + "<div>";
if (html[i]!=htmlPrevious[i]){
htmlPrevious[i]=html[i];
infoWindow[i].setContent(html[i]);
google.maps.event.addListener(marker, 'click', function() {
infoWindow[i].set("marker",null);
infoWindow[i].close();
bindInfoWindow(marker[i], map, infoWindow[i], html[i]);
infoWindow[i]=infoWindow;
});
}
//infoWindow.open(map, marker);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
alert("imhere");
});
}
function closeInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'closeclick', function() {
infoWindow.close();
alert("im here");
});
}
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()">
<div id="map" style="width: 1330px; height: 610px"></div>
</body>
</html>
Any help will highly appreciated.. :-)

Update your function to be:
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}

Related

Undefined length JSON AJAX return

I am getting an error:
Uncaught TypeError: Cannot read property 'length' of undefined
when I am trying to access my JSON through AJAX.
I double checked the JSON progression and it is correct from response->work.
The only time 'data' is used within is in this section.
Would this be the problem here? or is it in my process images function?
$.getJSON(url, function(data) {
$('#output').empty();
$.each(data.response.zone[0].records.work, processImages);
console.log(data);
printImages();
});
Process images function:
function processImages(index, troveItem){
for(var i in availableImages){
if(troveItem.identifier[0].value.indexOf(availableImages[i].url_pattern) >= 0){
console.log("Trove URL "+troveItem.identifier[0].value+" Pattern: "+availableImages[i]["url_pattern"]);
availableImages[i].numImages++;
availableImages.totalimages++;
availableImages[i]["images"].push(troveItem.identifier[0].value);
}
}
}
Whole code for reference:
<!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"/>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0-wip/js/bootstrap.min.js"></script>
<title>Supernatural Guide Map</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
Ghost: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
},
UFO: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
},
Yowie: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png'
},
Other: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_yellow.png'
}
};
var apiKey = "5d288qp21m735ekv";
var availableImages = {
"nla": {
"numImages":0,
"url_pattern":"nla.gov.au",
"images":[]
},
"totalimages":0,
};
var url_patterns = ["nla.gov.au"];
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(-25.3080, 134.1245),
zoom: 3,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml2.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 type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var description = markers[i].getAttribute("description");
///trove//
resetImageData();
//get input vals
//utf encoding// not sure if need tim etc and replace //if statement here for address or name
var searchTerm = markers[i].getAttribute("name");//.val().trim();
searchTerm = searchTerm.replace(/ /g,"%20");
var sortby = "relevence";
// create search query
var url = "http://api.trove.nla.gov.au/result?key="
+ apiKey + "&l-availability=y%2Ff&encoding=json&zone=picture"
+ "&sortby=relevance&n=100&q=" + searchTerm + "&callback=?";
//print JSON object
//console.log(url);
//get the JSON information we need to display the images
$.getJSON(url, function(data) {
$('#output').empty();
$.each(data.response.zone[0].records.work, processImages);
console.log(data);
printImages();
});
var iwContent = "<b>" + name + "</b> <br/>" + address;
var contentString = '<div id="content">'+
//'<div id="siteNotice">'+
//'</div>'+
'<h1 id="firstHeading" class="firstHeading">'+name+'</h1>'+
'<div id="bodyContent">'+
'<p>'+'<i>'+address+'<i>'+
'<p>'+'<i>'+type+'<i>'+
'<p>'+description+'</p>'+
//'<img id="output">'+
'<div id="output">'+'</div>'
'</div>'+
'</div>';
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
bindInfoWindow(marker, map, infoWindow, contentString);//iwContent);
}
});
}
function bindInfoWindow(marker, map, infoWindow, contentString) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(contentString);
maxWidth: 500;
infoWindow.open(map, marker);
});//addmarker will go here
google.maps.event.addListener(marker /*map*/, 'rightclick', function(){
infoWindow.setContent(iwContent);
infoWindow.open(map, marker);
});
}
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() {}
//]]>
///TROVE///////NEED TO INCORPOATE FLICKR//also when write is implemented, write image url for quick to db loading
function processImages(index, troveItem){
for(var i in availableImages){
if(troveItem.identifier[0].value.indexOf(availableImages[i].url_pattern) >= 0){
console.log("Trove URL "+troveItem.identifier[0].value+" Pattern: "+availableImages[i]["url_pattern"]);
availableImages[i].numImages++;
availableImages.totalimages++;
availableImages[i]["images"].push(troveItem.identifier[0].value);
}
}
}
function printImages(){
$("#output").append("<h3>Image Search Results</h3>");
for(var i in availableImages){
if(availableImages[i]["url_pattern"]=="nla.gov.au" && availableImages[i]["numImages"]>0){
printNLAImages();
}
}
}
function printNLAImages(){
$("#output").append("<h3>National Library of Australia</h3><p>"
+availableImages["nla"]["numImages"]+" images found from <a href='http://"
+availableImages["nla"]["url_pattern"]+"'>"
+availableImages["nla"]["url_pattern"]+"</a></p>");
for (var i in availableImages["nla"]["images"]){
$("#output").append("<img src='"+availableImages["nla"]["images"][i]+"-v'>");
}
}
function resetImageData(){
availableImages.totalimages = 0;
for (var i in availableImages){
availableImages[i].numImages = 0;
availableImages[i]["images"] = [];
}
//console.log(availableImages);
}
// from http://css-tricks.com/snippets/javascript/get-url-variables/
function getQueryVariable(variable, url)
{
var query = url.split("?");
var vars = query[1].split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
</script>
</head>
<body onload="load()">
<div id="map" style="width: 1000px; height: 600px;"></div>
</body>
</html>

Google Maps pass lat and long from InfoWindow to URL

I have this google map that passes the lat and long just fine in other versions. This version works displaying the marker just fine, which means within the map those value exist. However, when I click the map_more_button.png it doesn't send the link to the url specified.
Here's the working version:
http://goodnite.jp/tokyo/map/android_map_mobile.html
Here's the map that needs updating:
http://goodnite.jp/tokyo/map/android_map_mobile_single.html
Here's the code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--<meta http-equiv="content-type" content="text/html; charset=utf-8"/>-->
<meta http-equiv = "content-type" content = "text/html; charset = UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<!-- this is the part responsible for hidding the bottom bar -->
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>GOODNITE TOKYO ~ Locations Map (MOBILE)</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=true"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var map ;
var customIcons = {
club: {
icon: 'http://goodnite.jp/tokyo/map/marker_small_club.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'http://goodnite.jp/tokyo/map/marker_small_bar.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
karaoke: {
icon: 'http://goodnite.jp/tokyo/map/marker_small_karaoke.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
var styles = [{"stylers": [{ "invert_lightness": true }]}];
function load() {
//hideAddressBar();
var name ="";
var address = "";
var type = "";
var lat = "0.0";
var lng = "0.0";
var Url=window.location.href;//如果想获取框架顶部的url可以用 top.window.location.href
var u,g,StrBack='';
if(arguments[arguments.length-1]=="#")
u=Url.split("#");
else
u=Url.split("?");
if (u.length==1) g='';
else g=u[1];
if(g!=''){
var gg=g.split("&");
var MaxI=gg.length;
str = "lat=";
//for(xm=0;xm<MaxI;xm++){
if(gg[0].indexOf(str)==0) {
lat=gg[0].replace(str,"");
}
str="lng="
if(gg[1].indexOf(str)==0) {
lng=gg[1].replace(str,"");
}
str="name="
if(gg[2].indexOf(str)==0) {
name=decodeURI(gg[2].replace(str,""));
}
str="address="
if(gg[3].indexOf(str)==0) {
address=decodeURI(gg[3].replace(str,""));
}
str="type="
if(gg[4].indexOf(str)==0) {
type=gg[4].replace(str,"");
}
//}
}
var point = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
map = new google.maps.Map(document.getElementById("map"), {
center: point,
zoom: 17,
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var styledMap = new google.maps.StyledMapType(styles,{name: "Styled Map"});
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
//var html = "<b>" + name + "</b> <br/>" + address + "<br><span id='move_span'><a href='javascript:proMoreShow();'><img src='http://goodnitetokyo.com/mobile/images/map_more_button.png' width='48' height='16' /></a></span><span id='more_info' style='display:none;'>LAT: "+lat+" >LNG: "+lng+"</span>";
var html = "<b>" + name + "</b> <br/>" + address + "<br/><a href='javascript:directionsClick(\"" + point.toUrlValue() + "\");'><img src='http://goodnite.jp/tokyo/mobile/images/map_more_button.png' width='48' height='16' /></a>";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
var infoWindow = new google.maps.InfoWindow;
bindInfoWindow(marker, map, infoWindow, html);
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
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() {}
//var html = "<b>" + name + "</b> <br/>" + address + "<br/><a href='javascript:directionsClick(\"" + point.toUrlValue() + "\");'><img src='http://goodnite.jp/tokyo/mobile/images/map_more_button.png' width='48' height='16' /></a>";
function directionsClick(latlng){
var myURL = 'https://maps.google.com/maps?saddr=&daddr=' + latlng + '&sensor=TRUE';
//var myURL = 'comgooglemaps://?saddr=&daddr=' + latlng + '&sensor=TRUE';
//var myURL = 'geo:' + latlng + '?z=15';
window.open(myURL,"_blank");
}
function hideAddressBar()
{
if(!window.location.hash)
{
if(document.height < window.outerHeight)
{
document.body.style.height = (window.outerHeight + 50) + 'px';
}
setTimeout( function(){ window.scrollTo(0, 1); }, 50 );
}
};
}
function proMoreShow()
{
$("#move_span").css({display:"none"});
$("#more_info").css({display:"block"});
}
</script>
<link href="css/style.css" rel="stylesheet" type="text/css">
</head>
<body onLoad="load()">
<div id="map" style="width: 100%; height: 100%"></div>
</body>
</html>
Does some value need to be return, stored or something to properly pass it to the button?
Thanks for reading.
I've created a working JSFiddle from your example
I found the following problems with the Javascript you posted:
a. There was no closing bracket } for the load() function so I modified the code as follows:
...
var infoWindow = new google.maps.InfoWindow;
bindInfoWindow(marker, map, infoWindow, html);
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
}
b. The hideAddressBar() function was badly defined (it had an extra };). I removed this so the function is:
function hideAddressBar() {
if (!window.location.hash) {
if (document.height < window.outerHeight) {
document.body.style.height = (window.outerHeight + 50) + 'px';
}
setTimeout(function () {
window.scrollTo(0, 1);
}, 50);
}
}
The full code is:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!--<meta http-equiv="content-type" content="text/html; charset=utf-8"/>-->
<meta http-equiv="content-type" content="text/html; charset = UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<!-- this is the part responsible for hidding the bottom bar -->
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>GOODNITE TOKYO ~ Locations Map (MOBILE)</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=true" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var map;
var customIcons = {
club: {
icon: 'http://goodnite.jp/tokyo/map/marker_small_club.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'http://goodnite.jp/tokyo/map/marker_small_bar.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
karaoke: {
icon: 'http://goodnite.jp/tokyo/map/marker_small_karaoke.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
var styles = [{
"stylers": [{
"invert_lightness": true
}]
}];
function load() {
//hideAddressBar();
var name = "";
var address = "";
var type = "";
var lat = "0.0";
var lng = "0.0";
var Url = window.location.href; //??????????url??? top.window.location.href
var u, g, StrBack = '';
if (arguments[arguments.length - 1] == "#") u = Url.split("#");
else u = Url.split("?");
if (u.length == 1) g = '';
else g = u[1];
if (g != '') {
var gg = g.split("&");
var MaxI = gg.length;
str = "lat=";
//for(xm=0;xm<MaxI;xm++){
if (gg[0].indexOf(str) == 0) {
lat = gg[0].replace(str, "");
}
str = "lng="
if (gg[1].indexOf(str) == 0) {
lng = gg[1].replace(str, "");
}
str = "name="
if (gg[2].indexOf(str) == 0) {
name = decodeURI(gg[2].replace(str, ""));
}
str = "address="
if (gg[3].indexOf(str) == 0) {
address = decodeURI(gg[3].replace(str, ""));
}
str = "type="
if (gg[4].indexOf(str) == 0) {
type = gg[4].replace(str, "");
}
//}
}
var point = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));
map = new google.maps.Map(document.getElementById("map"), {
center: point,
zoom: 17,
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var styledMap = new google.maps.StyledMapType(styles, {
name: "Styled Map"
});
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
//var html = "<b>" + name + "</b> <br/>" + address + "<br><span id='move_span'><a href='javascript:proMoreShow();'><img src='http://goodnitetokyo.com/mobile/images/map_more_button.png' width='48' height='16' /></a></span><span id='more_info' style='display:none;'>LAT: "+lat+" >LNG: "+lng+"</span>";
var html = "<b>" + name + "</b> <br/>" + address + "<br/><a href='javascript:directionsClick(\"" + point.toUrlValue() + "\");'><img src='http://goodnite.jp/tokyo/mobile/images/map_more_button.png' width='48' height='16' /></a>";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
var infoWindow = new google.maps.InfoWindow;
bindInfoWindow(marker, map, infoWindow, html);
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
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() {}
//var html = "<b>" + name + "</b> <br/>" + address + "<br/><a href='javascript:directionsClick(\"" + point.toUrlValue() + "\");'><img src='http://goodnite.jp/tokyo/mobile/images/map_more_button.png' width='48' height='16' /></a>";
function directionsClick(latlng) {
var myURL = 'https://maps.google.com/maps?saddr=&daddr=' + latlng + '&sensor=TRUE';
//var myURL = 'comgooglemaps://?saddr=&daddr=' + latlng + '&sensor=TRUE';
//var myURL = 'geo:' + latlng + '?z=15';
window.open(myURL, "_blank");
}
function hideAddressBar() {
if (!window.location.hash) {
if (document.height < window.outerHeight) {
document.body.style.height = (window.outerHeight + 50) + 'px';
}
setTimeout(function() {
window.scrollTo(0, 1);
}, 50);
}
}
function proMoreShow() {
$("#move_span").css({
display: "none"
});
$("#more_info").css({
display: "block"
});
}
</script>
<link href="css/style.css" rel="stylesheet" type="text/css">
</head>
<body onLoad="load()">
<div id="map" style="width: 100%; height: 100%"></div>
</body>
</html>

Custom Google Maps API v3 - Javascript Sidebar Customization

After a lot of work/research/headaches, etc., I've got my "Local Business Directory" w/ Google Maps script working pretty cool.
Now, I'm stuck. There are a couple of things the app needs to do before it's done.
I need to run a query when someone logs on to the site, so that there is some data displayed in the sidebar... A kind of "Some Local Businesses".
I need some sort of filters to show up in a fixed cell/div at the top of the "sidebar" div. For example, sort by name desc/asc... or only show results that meet some sort of other criteria, only restaurants that offer on-line coupons, or only featured businesses, or only new businesses.
Here is my working script so far:
<script src="http://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript" src="js/gmap_markerwithlabel.js"></script>
<script type="text/javascript">
//<![CDATA[
google.maps.visualRefresh = true;
var map;
var markers = [];
var infoWindow;
var myCenter=new google.maps.LatLng(<?=$gmap_center_point?>);
<!-- FUNCTION -->
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(<?=$gmap_center_point?>),
zoom: 10,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
});
infoWindow = new google.maps.InfoWindow();
<!-- STICK A CUSTOM PIN IN CENTER LOCATION -->
var center_marker=new google.maps.Marker({
map:map,
position:myCenter,
clickable: true,
icon:'/images/GHV_map_marker.png'
});
center_marker.info = new google.maps.InfoWindow({
content: 'My Location'
});
google.maps.event.addListener(center_marker, 'click', function() {
center_marker.info.open(map, center_marker);
});
center_marker.setMap(map);
}
<!-- This function does the Search based on AddressInput -->
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');
}
});
}
<!-- FUNCTION -->
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
}
<!-- This function queries the Processing File based on criteria set... radius... search term. etc.-->
function searchLocationsNear(center) {
clearLocations();
var radius = document.getElementById('radiusSelect').value;
var searchrequest = document.getElementById('search').value;
var searchUrl = 'search_genxml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius + '&searchrequest=' + searchrequest;
downloadUrl(searchUrl, function(data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var sidebar = document.getElementById('sidebar');
sidebar.innerHTML = '';
if (markerNodes.length == 0) {
sidebar.innerHTML = 'No results found.';
map.setZoom(6);
map.setCenter(new google.maps.LatLng(<?=$gmap_center_point?>));
return;
}
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
<!-- GRAB THE VARIABLES ATTRIBUTES FROM PROCESSING FILE AND ASSIGN VAR -->
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var profile_link = markerNodes[i].getAttribute("profile_link");
var featured = markerNodes[i].getAttribute("featured");
var coupons = markerNodes[i].getAttribute("coupons");
var youtube_activate = markerNodes[i].getAttribute("youtube_activate");
var additional_photo = markerNodes[i].getAttribute("additional_photo");
var logo = markerNodes[i].getAttribute("logo");
var number_count = markerNodes[i].getAttribute("number_count");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
createSidebarEntry(name, address, distance, i, featured, coupons, youtube_activate, additional_photo, logo, profile_link, number_count);
createMarker(latlng, name, address, profile_link, number_count, distance);
bounds.extend(latlng);
}
map.fitBounds(bounds);
});
}
<!-- This function creates marker and populates the infobubble -->
function createMarker(latlng, name, address, profile_link, number_count, distance, zoom) {
var html = "<b>" + name + "</b> <br/>" + address + "<br/><font color=\"red\">Approx. " + distance.toFixed(1) + " miles away</font><br/>"
<!-- html += '<a class="menu" href="javascript: map.setZoom('+zoom+');">Zoom To</a>'; -->
html += ' <a class="menu" href="javascript:map.set(streetViewControl, true);">Street View</a>';
html += ' | ';
html += ' <a class="menu" href="javascript:map.setCenter(new google.maps.LatLng('+latlng.toUrlValue(6)+')); map.setZoom(parseInt(map.getZoom())+2);">Zoom In</a>';
html += ' | ';
html += ' <a class="menu" href="javascript:map.setCenter(new google.maps.LatLng('+latlng.toUrlValue(6)+')); map.setZoom(parseInt(map.getZoom())-2);">Out </a>';
html += '<br/><br/>'+ profile_link ;
var marker = new MarkerWithLabel({
map: map,
position: latlng,
animation: google.maps.Animation.DROP,
<!-- Label Options Reference http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.1.9/examples/-->
labelContent: number_count,
labelAnchor: new google.maps.Point(8, 36),
labelClass: "gmap_labels", // the CSS class for the label
labelInBackground: false
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers.push(marker);
}
<!-- This function . . . -->
function createSidebarEntry(name, address, distance, num, featured, coupons, youtube_activate, additional_photo, logo, profile_link, number_count) {
var div = document.createElement("div");
var html = '<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"5\"><tr><td width=\"20px\" valign=\"top\" align=\"right\">'+ number_count +'</td><td ><b>' + name + '</b> <br/><font color=\"red\">Approx. ' + distance.toFixed(1) + ' miles away.</font><br/>' + address + ' <br/><br/></td></tr></table>';
div.value = num;
div.innerHTML = html;
div.style.cursor = 'pointer';
div.style.marginBottom = '5px';
sidebar.appendChild(div);
google.maps.event.addDomListener(div, 'click', function() {
google.maps.event.trigger(markers[num], 'click');
});
google.maps.event.addDomListener(div, 'mouseover', function() {
div.style.backgroundColor = '#eee';
});
google.maps.event.addDomListener(div, 'mouseout', function() {
div.style.backgroundColor = '#fff';
});
return div ;
}
<!-- This function . . . -->
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);
}
<!-- This function . . . -->
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');
}
}
<!-- This function . . . -->
function doNothing() {}
//]]>
</script>

How to submit a zipcode to Google Map API via a form

I am working on this example from Google maps api
here
The map initializes according to the coordinates that are hard coded.My problem is the "addressInput" is not recognized and map just continues to display the same view . I think there is a problem with geocoder expression.
Here is my HTML file
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>ShopRight Store Locator</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var map;
var markers = [];
var infoWindow;
var locationSelect;
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(43.7, -79.4),
zoom: 11,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
infoWindow = new google.maps.InfoWindow();
locationSelect = document.getElementById("locationSelect");
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
if (markerNum != "none"){
google.maps.event.trigger(markers[markerNum], 'click');
}
};
}
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');
}
});
}
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);
}
function searchLocationsNear(center) {
clearLocations();
var radius = document.getElementById('radiusSelect').value;
var searchUrl = 'storelocator.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 hours = markerNodes[i].getAttribute("hours");
var phone = markerNodes[i].getAttribute("phone");
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
createOption(name, distance, i);
createMarker(latlng, name, address, hours, phone);
bounds.extend(latlng);
}
map.fitBounds(bounds);
locationSelect.style.visibility = "visible";
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
google.maps.event.trigger(markers[markerNum], 'click');
};
});
}
function createMarker(latlng, name, address, hours, phone) {
var html = "<b>" + name + "</b> <br/>" + address+"</b> <br/>" + hours+"</b> <br/>" +phone;
var marker = new google.maps.Marker({
map: map,
position: latlng
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
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);
}
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 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');
}
}
function doNothing() {}
Can someone point me into where to look into that. TIA

google maps not loading, showing just a '

So im using PHP/MySQL to load the information into a XML which works then I have this code below that is supposed to make the map and load the xml and plug it into the markers when clicked. This is almost 100% copy pasted from googles tutorial
https://developers.google.com/maps/articles/phpsqlajax_v3#createmap
Any help would be lovely I have been struggling with this for days
<!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 type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=my key&sensor=true"></script>
<script type="text/javascript">
//<![CDATA[
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng('34.153471', '-118.432123'),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("mapXML2.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 desc = markers[i].getAttribute("desc");
var cap = markers[i].getAttribute("eventcap");
var cur = markers[i].getAttribute("eventcur");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address + "<br/>" + desc + "<br/>" + "Currently " + cur + "/" + cap;
//var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
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()">
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>
You are missing closing bracket for load()
}
});
}//**ADD THIS**
function bindInfoWindow(marker, map, infoWindow, html) {

Categories

Resources