fusion table issues with onClick and custom icons - google-maps-api-3

I am trying to get layers to click on and off by using a checkbox, but for some reason I am missing something and can not get it to click on and off again. I also would like to add custom markers for each layer but have not succeeded in doing that at all.
Here is the code I am working with. I would appreciate any help on this I am so new to working with this code.
var map;
var layerl0;
var layerl1;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(62.683556,-152.314453),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
layerl0 = new google.maps.FusionTablesLayer({
query: {
select: "'col0'",
from: '1suBUHqahw5W9f6A6kEVhh-NWmqSbukYqdtnJLWs'
},
map: map,
styleId: 2,
templateId: 3
});
layerl1 = new google.maps.FusionTablesLayer({
query: {
select: "'col0'",
from: '1ra3TP6cbWmdAOayLgzCugLrhdmDAO6UJIFuty9E'
},
map: map,
styleId: 2,
templateId: 3
});
}
function changeMapl0() {
var searchString = document.getElementById('search-string-l0').value.replace(/'/g, "\\'");
layerl0.setOptions({
query: {
select: "'col0'",
from: '1suBUHqahw5W9f6A6kEVhh-NWmqSbukYqdtnJLWs',
where: "'category' = '" + searchString + "'"
}
});
}
function changeMapl1() {
var searchString = document.getElementById('search-string-l1').value.replace(/'/g, "\\'");
layerl1.setOptions({
query: {
select: "'col0'",
from: '1ra3TP6cbWmdAOayLgzCugLrhdmDAO6UJIFuty9E',
where: "'category' = '" + searchString + "'"
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div style="margin-top: 10px;">
<form>
<input type="checkbox" value="CRCD" checked="checked" id="search-string-l0" onClick="changeMapl0(this.value);">CRCD Learning Centers
<input type="checkbox" value="Research" checked="checked" id="search-string-l1" onClick="changeMapl1(this.value);">Off-site Research
</form>
</div>

Your problem is that your changeMap functions don't actually do anything based on the value of the checkbox:
function changeMapl0() {
var searchString = document.getElementById('search-string-l0').value.replace(/'/g, "\\'");
layerl0.setOptions({
query: {
select: "'col0'",
from: '1suBUHqahw5W9f6A6kEVhh-NWmqSbukYqdtnJLWs',
where: "'category' = '" + searchString + "'"
}
});
}
Try this instead:
function changeMapl0() {
if (document.getElementById('search-string-l0').checked )
{ layerl0.setMap(map); }
else
{ layerl0.setMap(null); }
}
Working example

Related

Google Place Search using SearchBox - Restrict for UK only

I am using google place SearchBox ( not AutoComplete ) for place search. My objective is I want to restrict the search for a particular country (UK).
I know the same thing can be achieved easily by using AutoComplete. But I can't use this because my map will populate on enter key as well as against a search button.
I am using code to select the first option on search button click.
I have tried with google.maps.LatLngBounds but that only sets the priority of result, not restricting anything.
Html:
<ul class="list-unstyled search-branch">
<li>Search branches:</li>
<li><input type="text" placeholder="City, town or postcode" id="txtbranch" value="Eurochange" />
<input type="button" class="button gold" id="getbranch" value="Search" />
<div style="clear:both;"></div>
<div class="error-message-summary" id="locationnotfound" style="padding: 0;top:-30px; position:relative; font-size:16px;display:none">
No search results found.
</div>
</li>
</ul>
js:
var input = document.getElementById('txtbranch');
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 1512631)
);
var options = {
bounds: defaultBounds
}
var searchBox = new google.maps.places.SearchBox(input, {
bounds: defaultBounds
});
$('#getbranch').click(function () {
var input = document.getElementById('txtbranch');
if (BranchAddressSelector.val() == "") {
return;
}
google.maps.event.trigger(input, 'focus');
google.maps.event.trigger(input, 'keydown', { keyCode: 13 });
return false;
})
searchBox.addListener('places_changed', function () {
var places = searchBox.getPlaces()[0];
if (typeof (places) === "undefined") {
locationNotFoundSelector.css("display", "block");
return false;
}
if (BranchAddressSelector.val() == "") {
return false;
}
var address = places.formatted_address;
if (typeof (address) === "undefined") {
locationNotFoundSelector.css("display", "block");
return false;
}
var latitude = places.geometry.location.lat();
var longitude = places.geometry.location.lng();
$.ajax({
type: "GET",
url: BranchLocatorUrl.GetBranches,
data: { Latitude: latitude, longitude: longitude },
success: function (data) {
if (data.length > 0) {
markers = data;
LoadMap(0, 0);
BranchListSelector.html(CreateSearchHtml(markers));
goToByScroll("dvMap");
BranchListSelector.css("display", "none");
paginationSelector.css("display", "none");
$('.map-distance').css("display", "block");
locationNotFoundSelector.css("display", "none");
var show_per_page = 6;
var number_of_items = BranchListSelector.children('.BranchItem').size();
var number_of_pages = Math.ceil(number_of_items / show_per_page);
totalPages = number_of_pages;
$('#current_page').val(0);
$('#show_per_page').val(show_per_page);
var navigation_html = '<a class="previous_link" style="color: #007ea0;" href="javascript:previous();">Prev</a> ';
var current_link = 0;
while (number_of_pages > current_link) {
navigation_html += '<a class="page_link" style="color: #007ea0;" href="javascript:go_to_page(' + current_link + ')" longdesc="' + current_link + '">' + (current_link + 1) + '</a> ';
current_link++;
}
navigation_html += '<a class="next_link" style="color: #007ea0;" href="javascript:next();"> Next</a>';
$('#page_navigation').html(navigation_html).css("float", "right").css("display", "none");
$('#page_navigation .page_link:first').addClass('active_page');
BranchListSelector.children('.BranchItem').css('display', 'none');
BranchListSelector.children('.BranchItem').slice(0, show_per_page).css('display', 'block');
BranchListSelector.css("display", "block");
// paginationSelector.css("display", "block");
$('.map-distance').css("display", "none");
$('#moreBranch').css("display", "block");
}
else {
alert("Data not found.");
}
},
error: function (e) {
alert("Some Problem occurs.Try after some time");
return;
}
});
});

Show Viewbag data in Google Map using ASP.NET MVC

I have json file for a City which contain Many Interesting places name,Short-text, Geocoordinates and Image. I deserialize this json data in Controller. Now I want to show this information as Viewbag in the View in google map.Well I am trying but there are lots of error in my code and nothing work at all. My sample json data is as follows-
{
"poi":[
{
"Name": "Nordertor",
"Shorttext": "The Nordertor is an old town gate in Flensburg, Germany, which was built around 1595. Today the landmark is used as a symbol for Flensburg.",
"GeoCoordinates": {
"Longitude": 9.43004861,
"Latitude": 54.79541778
},
"Images": [
"https://upload.wikimedia.org/wikipedia/commons/thumb/6/6b/Nordertor_im_Schnee_%28Flensburg%2C_Januar_2014%29.JPG/266px-Nordertor_im_Schnee_%28Flensburg%2C_Januar_2014%29.JPG"
]
},
{
"Name": "Naval Academy Mürwik",
"Shorttext": "The Naval Academy Mürwik is the main training establishment for all German Navy officers and replaced the German Imperial Naval Academy in Kiel.\nIt is located at Mürwik which is a part of Germany's most northern city, Flensburg. Built on a small hill directly by the coast, it overlooks the Flensburg Fjord. The main building of the academy is known for its beautiful architecture and location, and is often named the \"Red Castle\".",
"GeoCoordinates": {
"Longitude": 9.45944444,
"Latitude": 54.815
},
"Images": [
"https://upload.wikimedia.org/wikipedia/commons/thumb/f/fb/MSM-hauptgebaeude.jpg/400px-MSM-hauptgebaeude.jpg"
]
},
{
"Name": "Flensburg Firth",
"Shorttext": "Flensburg Firth or Flensborg Fjord is the westernmost inlet of the Baltic Sea. It forms part of the border between Germany to the south and Denmark to the north. Its length is either 40 or 50 km, depending to the definition of its limits. It has the largest surface of all Förden and East Jutland Fjorde, which are a special type of inlets, different from geological fjords.\nTwo peninsulas, Broager peninsula on the northern side and Holnis peninsula on the southern side divide the inlet in an outer and an inner part. West of them, near the Danish coast, there are two small Islands called Okseøer.\nOn the Danish side, outer part of the northern limits of the firth is formed by the island of Als with the town of Sønderborg. Towards the west, continuing on the Danish side are Broager, Egernsund, Gråsten, Rinkenæs, Sønderhav, and Kollund.\nIn Germany at the Danish border there is Harrislee, at the inner end of the inlet the town of Flensburg, east of it on the southern shore the town of Glücksburg and the villages Munkbrarup, Langballig, Westerholz, Quern, Steinberg, Niesgrau, Gelting, and Nieby.\n\n",
"GeoCoordinates": {
"Longitude": 9.42901993,
"Latitude": 54.7959404
},
"Images": [
"https://upload.wikimedia.org/wikipedia/commons/thumb/8/8c/Flensborg_Fjord_ved_bockholmwik.jpg/400px-Flensborg_Fjord_ved_bockholmwik.jpg"
]
}
]
}
In the Controller class I deserilize in the following way-
public ActionResult Index(City objCityModel)
{
string name = objCityModel.Name;
return View();
}
public ActionResult PlaceInformation(City objCityModel)
{
string name = objCityModel.Name;
ViewBag.Title = name;
var ReadJson = System.IO.File.ReadAllText(Server.MapPath(#"~/App_Data/POI_Json/" + name + ".json"));
RootObject json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<RootObject>(ReadJson);
List<Poi> mycities = new List<Poi>();
foreach (var item in json.poi)
{
Poi obj = new Poi()
{
Name = item.Name,
Shorttext = item.Shorttext,
GeoCoordinates = item.GeoCoordinates,
Images = item.Images,
};
mycities.Add(obj);
}
ViewBag.Cities = mycities;
return View();
}
Now in the View I want to use this data. But I ma not how to proceed with it. I wrote some comments beside the code.
#model PoiFinder.Models.City
<div class="row wrapper border-bottom white-bg page-heading">
<div class="col-lg-10">
<h2>#ViewBag.Title</h2>
<ol class="breadcrumb">
<li class="active">
Back
</li>
</ol>
</div>
</div>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>GoogleMap</title>
</head>
<body>
<script src="http://maps.google.com/maps/api/js?sensor=true" type="text/javascript"></script>
<!-- This css is to ensure that the google map contols (zoom bar etc) show and size correctly. -->
<style>
#map_canvas img {
max-width: none;
}
</style>
<!-- This css is to give a nice big popup "info window" when a marker is clicked on the map -->
<style>
.infoDiv {
height: 200px;
width: 300px;
-webkit-user-select: none;
background-color: white;
}
</style>
<div id="map_canvas" style="height: 600px;"></div>
#section scripts {
<section class="scripts">
<script type="text/javascript">
$(document).ready(function () {
Initialize();
});
function Initialize() {
google.maps.visualRefresh = true;
#ViewBag.Title = new google.maps.LatLng(53.408841, -2.981397); #*# Here I want to get the name of City#*#
var mapOptions = {
zoom: 14,
center: Liverpool,
mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var myLatlng = new google.maps.LatLng(53.40091, -2.994464);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Tate Gallery'
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')
$.each(ViewBag.Cities, function (i, item) {
var marker = new google.maps.Marker({
'position': new google.maps.LatLng(item.GeoCoordinates.Longitude, item.GeoCoordinates.Latitude),
'map': map,
'title': item.Name
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png')
var infowindow = new google.maps.InfoWindow({
content: "<div class='infoDiv'><h2>" + item.Name+ "</h2>" + "<div><h4>Short-Text: " + item.Shorttext + "</h4></div> +<div><img src=item#image </div>"
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
})
}
</script>
</section>
}
</body>
</html>
Example looks like this. You can build upon it
$(document).ready(function () {
ShowSuppliersOnGoogleMap();
});
function ShowSuppliersOnGoogleMap() {
var mapOptions = {
center: new google.maps.LatLng(42, -97)
, zoom: 4
, mapTypeId: google.maps.MapTypeId.ROADMAP
, mapTypeControl: true
, scrollwheel: false
};
var mapExists = document.getElementById("supplierMapCanvas");
if (mapExists) {
// init map
console.log('Initialise map...');
var map = new google.maps.Map(document.getElementById("supplierMapCanvas"), mapOptions);
getSupplierlistAndCreateGoogleMap(map);
}
}
function getSupplierlistAndCreateGoogleMap(map) {
var params={};
$.ajax({
type: "POST",
url: "/Home/GetSupplierInformationForGoogleMap",
data: AddAntiForgeryToken(params),
dataType: "json",
success: function (data) {
if (data.responseText != "") {
CreateSupplierMarker(data, map);
}
},
error: function (xhr, ajaxOptions, thrownError) {
logError(ajaxOptions, thrownError);
}
});
}
function CreateSupplierMarker(data, maps) {
var locations = [[]];
locations = data;
var total_locations = locations.length;
var map = maps;
var infoWindow = new google.maps.InfoWindow;
if (locations[0][0] != "NO-DATA") {
for (var i = 0; i < locations.length; i++) {
var supplierName = locations[i][0];
var address = locations[i][1];
var z = i;
// use the Google API to translate addresses to GPS coordinates
var geocoder = new google.maps.Geocoder();
if (geocoder) {
console.log('Got a new instance of Google Geocoder object');
console.log('Looking up ' + supplierName + ' at address ' + address);
geocoder.geocode({ 'address': address }, makeCallback(infoWindow, supplierName, z));
}
else {
console.log('Failed to instantiate Google Geocoder object');
}
}
}
else { console.log('Failed to retrieve supplier list'); }
function makeCallback(infoWindow, supplierName, zIndex) {
var geocodeCallBack = function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var longitude = results[0].geometry.location.lng();
var latitude = results[0].geometry.location.lat();
console.log('Received result: lat:' + latitude + ' long:' + longitude);
var content = '<div class="map-content"><h3>' + supplierName + '</h3></div>';
var marker = new google.maps.Marker({
position: new google.maps.LatLng(latitude, longitude),
map: map,
title: supplierName,
zIndex: zIndex
});
google.maps.event.addListener(marker, 'mouseover', (function (marker, content) {
return function () { infoWindow.setContent(content); infoWindow.open(map, marker); }
})(marker, content));
google.maps.event.addListener(marker, 'click', function () {
map.panTo(this.getPosition());
map.setZoom(15);
});
}
else {
console.log('No results found: ' + status);
}
}
return geocodeCallBack;
}
}
For your help Server side code looks like
[HttpPost]
public ActionResult GetSupplierInformationForGoogleMap()
{
string[][] supplierDetails = null;
try
{
logger.Info("Get Supplier Information For GoogleMap");
SupplierMapManager supplierMapManager = new SupplierMapManager();
supplierDetails = supplierMapManager.RetrieveSupplierList();
}
catch (Exception)
{
logger.Info("Get Supplier Information For GoogleMap failed");
throw;
}
return Json(supplierDetails, JsonRequestBehavior.AllowGet);
}

zoomToAddress not working on Google Fusion Map

I've followed the search and zoom example from here: https://developers.google.com/fusiontables/docs/samples/search_and_zoom
and I've managed to get the "Reset" button to work, but the "Search" button isn't working. I wondered if it was because I am using 2 layers, but I don't know how to correct by java script if that is that case. Any help appreciated. Thanks.
<html>
<head>
<meta charset="UTF-8">
<title>Smithfield Foods UK</title>
<link rel="stylesheet" type="text/css" media="all" href="FusionMapTemplate.css" />
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
var defaultZoom = 10;
var defaultCenter = new google.maps.LatLng(52.6500, 1.2800)
var locationColumn = 'geometry'
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: defaultCenter,
zoom: defaultZoom,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infoWindow = new google.maps.InfoWindow();
// Initialize the first layer
var FirstLayer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1hpGzmMBg8bDgPOGrAXvc0_QVLSBqQ0O5vpLbfUE'
},
map: map,
styleId: 3,
templateId: 5,
suppressInfoWindows: true
});
google.maps.event.addListener(FirstLayer, 'click', function(e) {windowControl(e, infoWindow, map);
});
// Initialize the second layer
var SecondLayer = new google.maps.FusionTablesLayer({
query: {
select: 'PostCode',
from: '1RrCcRC-1vU0bfHQJTQWqToR-vllSsz9iKnI5WEk'
},
map: map,
styleId: 2,
templateId: 2,
suppressInfoWindows: true
});
google.maps.event.addListener(SecondLayer, 'click', function(e) {windowControl(e, infoWindow, map);
});
var legend = document.createElement('div');
legend.id = 'legend';
var content = [];
content.push('<h3>Density of Polish speaking population</h3>');
content.push('<p><div class="color red1"></div>=>2%<4%');
content.push('<p><div class="color red2"></div>=>4%<6%');
content.push('<p><div class="color red3"></div>=>6%<10%');
content.push('<p><div class="color red4"></div>=>10%<15%');
content.push('<p><div class="color red5"></div>=>15%<20%')
content.push('<p><img src="Smithfield Black.png" alt="Smithfield Logo" width ="120px">');
legend.innerHTML = content.join('');
legend.index = 1;
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legend);
var legend2 = document.createElement('div');
legend2.id = 'legend2';
var content2 = [];
content2.push("<h3>Smithfield Food's sales in Asda Stores</h3>");
content2.push('<p><img src="red-dot.png"><£1,000');
content2.push('<p><img src="yellow-dot.png">=>£1,000<£20,000');
content2.push('<p><img src="green-dot.png">=>£20,000<£40,000');
legend2.innerHTML = content2.join('');
legend2.index = 1;
map.controls[google.maps.ControlPosition.RIGHT_TOP].push(legend2);
var zoomToAddress = function() {
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);
map.setZoom(10);
} else {
window.alert('Address could not be geocoded: ' + status);
}
});
};
google.maps.event.addDomListener(document.getElementById('search'), 'click', zoomToAddress);
google.maps.event.addDomListener(window, 'keypress', function(e) {
if (e.keyCode ==13) {
zoomToAddress();
}
});
google.maps.event.addDomListener(document.getElementById('reset'), 'click', function() {
map.setCenter(defaultCenter);
map.setZoom(defaultZoom);
layer.setOptions({
query: {
select: 'geometry',
from: '1hpGzmMBg8bDgPOGrAXvc0_QVLSBqQ0O5vpLbfUE'
}
});
});
}
// Open the info window at the clicked location
function windowControl(e, infoWindow, map) {
infoWindow.setOptions({
content: e.infoWindowHtml,
position: e.latLng,
pixelOffset: e.pixelOffset
});
infoWindow.open(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div>
<label>Enter an address:</label>
<input type="text" id="address" value="Leeds">
<input type="button" id="search" value="Search">
<input type="button" id="reset" value="Reset">
</div>
</body>
</html>
I get a "geocoder is undefined" error". Because it isn't defined.
One way to fix it would be to add this to the global scope (just before your initialize function):
var geocoder = new google.maps.Geocoder();
Or you could do it the way it is done in the example you used, it is inside the initialize function there.
working example

Switching between layers in Google Fusion Map using drop down box

Having successfully followed some Fusion Map examples, with a little help from people here. I'm trying to do something I've been able to find an example of...
My map contains 3 layers, but I only want to show 2 at a time. I've therefore added a drop down box at the bottom so that you can switch between 2 of the maps. I've added a variable "SecondLayerMap", and I think (i've at least tried) to get the drop down box to change this variable. I'd never written any Java (or any other programming language) until 3 weeks ago, so it's been a steep learning curve!
[One method I've seen some people use in a similar situation has been to use 1 fusion table, but switch between data in different columns. I don't think I can do this because the geodata in each table is different and I don't want them both displayed at the same time.]
The next step will be to change one of the legends with the switch in map, but I'll take what i learn from this problem, before tackling that one...
Thanks for your help.
<meta charset="UTF-8">
<title>Smithfield Foods UK</title>
<link rel="stylesheet" type="text/css" media="all" href="FusionMapTemplate.css" />
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
var defaultZoom = 10;
var defaultCenter = new google.maps.LatLng(52.6500, 1.2800);
var locationColumn = 'geometry';
var geocoder = new google.maps.Geocoder();
var SecondLayerMap = '1RrCcRC-1vU0bfHQJTQWqToR-vllSsz9iKnI5WEk'
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: defaultCenter,
zoom: defaultZoom,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infoWindow = new google.maps.InfoWindow();
// Initialize the first layer
var FirstLayer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1hpGzmMBg8bDgPOGrAXvc0_QVLSBqQ0O5vpLbfUE'
},
map: map,
styleId: 3,
templateId: 5,
suppressInfoWindows: true
});
google.maps.event.addListener(FirstLayer, 'click', function(e) {windowControl(e, infoWindow, map);
});
// Initialize the second layer
var SecondLayer = new google.maps.FusionTablesLayer({
query: {
select: 'PostCode',
from: SecondLayerMap
},
map: map,
styleId: 2,
templateId: 2,
suppressInfoWindows: true
});
google.maps.event.addDomListener(document.getElementById('store'), 'change', function() {
var SecondLayerMap = this.value;
SecondLayer = new google.maps.FusionTablesLayer({
query: {
select: 'Postcode',
from: SecondLayerMap
}
});
});
google.maps.event.addListener(SecondLayer, 'click', function(e) {windowControl(e, infoWindow, map);
});
var legend = document.createElement('div');
legend.id = 'legend';
var content = [];
content.push('<h3>Density of Polish speaking population</h3>');
content.push('<p><div class="color red1"></div>=>2%<4%');
content.push('<p><div class="color red2"></div>=>4%<6%');
content.push('<p><div class="color red3"></div>=>6%<10%');
content.push('<p><div class="color red4"></div>=>10%<15%');
content.push('<p><div class="color red5"></div>=>15%<20%')
content.push('<p><img src="Smithfield Black.png" alt="Smithfield Logo" width ="120px">');
legend.innerHTML = content.join('');
legend.index = 1;
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legend);
var legend2 = document.createElement('div');
legend2.id = 'legend2';
var content2 = [];
content2.push("<h3>Smithfield Food's sales in Asda Stores</h3>");
content2.push('<p><img src="red-dot.png"><£1,000');
content2.push('<p><img src="yellow-dot.png">=>£1,000<£20,000');
content2.push('<p><img src="green-dot.png">=>£20,000<£40,000');
legend2.innerHTML = content2.join('');
legend2.index = 1;
map.controls[google.maps.ControlPosition.RIGHT_TOP].push(legend2);
var zoomToAddress = function() {
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);
map.setZoom(10);
} else {
window.alert('Address could not be geocoded: ' + status);
}
});
};
google.maps.event.addDomListener(document.getElementById('search'), 'click', zoomToAddress);
google.maps.event.addDomListener(window, 'keypress', function(e) {
if (e.keyCode ==13) {
zoomToAddress();
}
});
google.maps.event.addDomListener(document.getElementById('reset'), 'click', function() {
map.setCenter(defaultCenter);
map.setZoom(defaultZoom);
layer.setOptions({
query: {
select: 'geometry',
from: '1hpGzmMBg8bDgPOGrAXvc0_QVLSBqQ0O5vpLbfUE'
}
});
});
}
// Open the info window at the clicked location
function windowControl(e, infoWindow, map) {
infoWindow.setOptions({
content: e.infoWindowHtml,
position: e.latLng,
pixelOffset: e.pixelOffset
});
infoWindow.open(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div>
<label>Enter an address:</label>
<input type="text" id="address" value="Leeds">
<input type="button" id="search" value="Search">
<input type="button" id="reset" value="Reset">
</div>
<div>
<select id="store">
<option value ="1RrCcRC-1vU0bfHQJTQWqToR-vllSsz9iKnI5WEk">Store A</option>
<option value ="1QX6QXhAiHXXAcS96RSAmE1Caj8tWebc6d-1_Tjk">Store B</option>
</select>
</body>
Use setOptions() to apply the query to the layer:
google.maps.event.addDomListener(document.getElementById('store'),
'change',
function() {
var SecondLayerMap = this.value;
SecondLayer.setOptions({
query: {
select: 'Postcode',
from: SecondLayerMap
}
});

Google Maps Api v3: Info window displaying same information for all the markers on the map

I'm working on this code for a certificate program, I tried to get some help from the instructors but they don't seem familiar with Google Map Apis and the requirement is to display multiple markers from addresses stores in an XML file once a search is performed, i.e I look for John, I get his markers in addition to markers for all of the people whose address is stored and specified in my XML file. So the goal is to be able to display say 5 markers for 5 people and their respective info windows.
I'm able to get all markers to display once a search is performed, I can also get the info windows but the info displayed in all info windows is the same in all markers, it displays the information for the name searched for. You could if you want test with the name Larry, zoom out to other markers and see that they all display the same name. I have no idea why? When I looked at fixes, I found nothing for google API v3 only stuff link a bindEvent for the Api v2. Any help would be highly appreciated, I don't know how to stop the for loop from making all the info windows the same. Thanks.
The code is bellow:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var geocoder;
var map;
var marker;
function load() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(37.4419, -122.1419);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("mymap"), myOptions);
}
function showAddress(theAddress) {
var myaddress = theAddress
if (geocoder) {
geocoder.geocode( { 'address': myaddress}, 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
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
function showAllAddress(AllAddress) {
var myaddress = AllAddress
if (geocoder) {
geocoder.geocode( { 'address': myaddress}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
// Create Info Window
var infowindow = new google.maps.InfoWindow({
content: document.getElementById("theName").innerHTML = fiobj[0].firstChild.data + " " + lastobj[0].firstChild.data+"<br />" + addressobj[0].firstChild.data+"<br />" + phoneobj[0].firstChild.data+"<br />" + emailobj[0].firstChild.data+"<br />"
});
// click event for marker
google.maps.event.addListener(marker, 'click', function() {
// Opening the InfoWindow
infowindow.open(map, marker);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
function createRequestObject() {
var ro
var browser = navigator.appName
if(browser == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP")
}else{
ro = new XMLHttpRequest()
}
return ro
}
var http = createRequestObject()
function sndReq() {
http.open('get', 'http://idrir.userworld.com/ajax/gmap.xml', true)
http.onreadystatechange = handleResponse
http.send(null)
}
function handleResponse() {
if(http.readyState == 4){
document.getElementById("theName").innerHTML = ""
document.getElementById("address").innerHTML = ""
document.getElementById("phone").innerHTML = ""
document.getElementById("email").innerHTML = ""
var response = http.responseXML.documentElement
listings=response.getElementsByTagName("LISTING")
for (i=0;i<listings.length;i++) {
firstobj = listings[i].getElementsByTagName("FIRST")
if (firstobj[0].firstChild.data == document.getElementById("first").value){
fiobj = listings[i].getElementsByTagName("FIRST")
lastobj = listings[i].getElementsByTagName("LAST")
addressobj = listings[i].getElementsByTagName("ADDRESS")
phoneobj = listings[i].getElementsByTagName("PHONE")
emailobj = listings[i].getElementsByTagName("EMAIL")
//do not use this code bellow
// document.getElementById("theName").innerHTML = firstobj[0].firstChild.data + " " + lastobj[0].firstChild.data
// document.getElementById("address").innerHTML = addressobj[0].firstChild.data
// document.getElementById("phone").innerHTML = phoneobj[0].firstChild.data
// document.getElementById("email").innerHTML = emailobj[0].firstChild.data
theAddress = addressobj[0].firstChild.data
showAddress(theAddress)
}
}
//added for loop to add markers
for (i=0;i<listings.length;i++) {
fobj = listings[i].getElementsByTagName("FIRST")
lobj = listings[i].getElementsByTagName("LAST")
aobj = listings[i].getElementsByTagName("ADDRESS")
pobj = listings[i].getElementsByTagName("PHONE")
eobj = listings[i].getElementsByTagName("EMAIL")
AllAddress = aobj[0].firstChild.data
showAllAddress(AllAddress)
}
}
}
</script>
</head>
<body onload="load()">
<form id="search">
<input type="text" id="first" />
<input type="button" value="Search Phonebook" onClick="sndReq()" />
</form>
<div id="theName"></div>
<div id="address"></div>
<div id="phone"></div>
<div id="email"></div>
<div id="mymap" style="width: 500px; height: 300px"></div>
</body>
</html>
I use this and it works... but I'm not a pro: my issue right now
var image = 'http://localhost:3000/images/icons/map/icons/icehockey.png';
var myLatlng_1 = new google.maps.LatLng(53.9515,-113.116);
var contentString_1 = "<b>Provident Place (formerly Redwater Multiplex) Ice Rink</b><br> Redwater, Alberta, Canada<br><b><a href='http://localhost:3000/rink/redwater/provident-place-formerly-redwater-multiplex'>Go To The Rink's Profile</a></b>";
var infowindow_1 = new google.maps.InfoWindow({content: contentString_1});
var marker_1 = new google.maps.Marker({
position: myLatlng_1,
map: map,
icon: image
});
google.maps.event.addListener(marker_1, 'click', function() {
infowindow_1.open(map,marker_1);
});
var myLatlng_2 = new google.maps.LatLng(53.4684,-113.409);
var contentString_2 = "<b>Ridgewood Skating Rink Ice Rink</b><br> Edmonton, Alberta, Canada<br><b><a href='http://localhost:3000/rink/edmonton/ridgewood-skating-rink'>Go To The Rink's Profile</a></b>";
var infowindow_2 = new google.maps.InfoWindow({content: contentString_2});
var marker_2 = new google.maps.Marker({
position: myLatlng_2,
map: map,
icon: image
});

Resources