Add 'See on Map' Link in Fusion Tables Map List View - google-maps-api-3

I am using the wonderful Fusion Tables Map Template by Derek Eder. I have activated the results list as instructed by him here.
I would like to have a 'See on Map' link on each listing so that when i click on the link the page scrolls up to the map and opens an infowindow for that particular listing. You can see an example on the geo places theme.
Below is my code
HTML
<!DOCTYPE html>
<html lang='en'>
<head>
<link rel="stylesheet" href="bootstrap.spacelab.min.css"/>
<link rel="stylesheet" href="bootstrap-responsive.min.css"/>
<link rel="stylesheet" href="custom.css"/>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
</head>
<body>
<div class='navbar'>
<div class='navbar-inner'>
<div class='container'>
<a class='brand' href='/'>Worldwide Stores</a>
</div>
</div>
</div>
<div class='container-fluid'>
<div class='row-fluid'>
<div class='span4'>
<div class='well'>
<h4>
Address <small>(<a id='find_me' href='#'>find me</a>)</small>
</h4>
<input class='input-block-level' id='search_address' placeholder='Enter an address or an intersection' type='text' />
<label>
show companies within
<select class='input-small' id='search_radius'>
<option value='400'>2 blocks</option>
<option value='805'>1/2 mile</option>
<option value='1610'>1 mile</option>
<option value='3220'>2 miles</option>
<option value='8050'>5 miles</option>
<option value='16100'>10 miles</option>
<option value='40250'>25 miles</option>
<option value='80500'>50 miles</option>
<option value='161000'>100 miles</option>
<option value='402500'>250 miles</option>
<option value='805000'>500 miles</option>
<option value='1610000'>1000 miles</option>
</select>
</label>
<h5> Refine Your Search By:</h5>
<label>
<select id='select_type'>
<option value=''>All Categories</option>
<option value='Hotels'>Hotels</option>
<option value='Restaurants'>Restaurants</option>
<option value='Shopping Malls'>Shopping Malls</option>
<option value='Travel Agents'>Travel Agents</option>
</select>
</label>
<label>
<select disabled id='select_type1'>
<option value=''>Select Two</option>
<option value='male'>Male</option>
<option value='female'>Female</option>
</select>
</label>
<label>
<select disabled id='select_type2'>
<option value=''>Select Three</option>
<option value='Advanced Materials/Prd'>Advanced Materials/Prd</option>
<option value='Advertising Agencies'>Advertising Agencies</option>
<option value='Advertising Sales'>Advertising Sales</option>
<option value='Advertising Services'>Advertising Services</option>
</select>
</label>
<input class='btn btn-primary' id='search' type='button' value='Search' />
<button class='btn' id='reset'>Reset</button>
</div>
<p class='alert alert-info lead' id='result_count'></p>
</p> </p>
</p> </p>
</p> </p>
</div>
<div class='span8'>
<div id='map_canvas'></div>
<div class='well'>
<div id='results_list'></div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="source/jquery.js"></script>
<script type="text/javascript" src="source/bootstrap.js"></script>
<script type="text/javascript" src="source/jquery.address.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript" src="source/jquery.geocomplete.min.js"></script>
<script type="text/javascript" src="maps_lib.js"></script>
<script type='text/javascript'>
//<![CDATA[
$(window).resize(function () {
var h = $(window).height(),
offsetTop = 90; // Calculate the top offset
$('#map_canvas').css('height', (h - offsetTop));
}).resize();
$(function() {
MapsLib.initialize();
$("#search_address").geocomplete();
$(':checkbox').click(function(){
MapsLib.doSearch();
});
$(':radio').click(function(){
MapsLib.doSearch();
});
$('#search_radius').change(function(){
MapsLib.doSearch();
});
$('#select_type').change(function(){
MapsLib.doSearch();
});
$('#select_type1').change(function(){
MapsLib.doSearch();
});
$('#select_type2').change(function(){
MapsLib.doSearch();
});
$('#search').click(function(){
MapsLib.doSearch();
});
$('#find_me').click(function(){
MapsLib.findMe();
return false;
});
$('#reset').click(function(){
$.address.parameter('address','');
MapsLib.initialize();
return false;
});
$(":text").keydown(function(e){
var key = e.keyCode ? e.keyCode : e.which;
if(key == 13) {
$('#search').click();
return false;
}
});
});
//]]>
</script>
</body>
</html>
maps_lib.js
/*!
* Searchable Map Template with Google Fusion Tables
* http://derekeder.com/searchable_map_template/
*
* Copyright 2012, Derek Eder
* Licensed under the MIT license.
* https://github.com/derekeder/FusionTable-Map-Template/wiki/License
*
* Date: 12/10/2012
*
*/
var MapsLib = MapsLib || {};
var MapsLib = {
//Setup section - put your Fusion Table details here
//Using the v1 Fusion Tables API. See https://developers.google.com/fusiontables/docs/v1/migration_guide for more info
//the encrypted Table ID of your Fusion Table (found under File => About)
//NOTE: numeric IDs will be deprecated soon
fusionTableId: "1f8rnajgS2iSVwwBR1NwXwImUuFB7VCpOg1-IfCs",
//*New Fusion Tables Requirement* API key. found at https://code.google.com/apis/console/
//*Important* this key is for demonstration purposes. please register your own.
googleApiKey: "API KEY",
//name of the location column in your Fusion Table.
//NOTE: if your location column name has spaces in it, surround it with single quotes
//example: locationColumn: "'my location'",
locationColumn: "Address",
map_centroid: new google.maps.LatLng(17,15), //center that your map defaults to
locationScope: "", //geographical area appended to all address searches
recordName: "Store", //for showing number of results
recordNamePlural: "Stores",
searchRadius: 805, //in meters ~ 1/2 mile
defaultZoom: 2, //zoom level when map is loaded (bigger is more zoomed in)
addrMarkerImage: 'http://derekeder.com/images/icons/blue-pushpin.png',
currentPinpoint: null,
initialize: function() {
$( "#result_count" ).html("");
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: MapsLib.defaultZoom,
center: MapsLib.map_centroid,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($("#map_canvas")[0],myOptions);
// maintains map centerpoint for responsive design
google.maps.event.addDomListener(map, 'idle', function() {
MapsLib.calculateCenter();
});
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(MapsLib.map_centroid);
});
MapsLib.searchrecords = null;
//reset filters
$("#search_address").val(MapsLib.convertToPlainString($.address.parameter('address')));
var loadRadius = MapsLib.convertToPlainString($.address.parameter('radius'));
if (loadRadius != "") $("#search_radius").val(loadRadius);
else $("#search_radius").val(MapsLib.searchRadius);
$(":checkbox").attr("checked", "checked");
$("#result_count").hide();
//-----custom initializers-------
//run the default search
MapsLib.doSearch();
},
doSearch: function(location) {
MapsLib.clearSearch();
var address = $("#search_address").val();
MapsLib.searchRadius = $("#search_radius").val();
var whereClause = MapsLib.locationColumn + " not equal to ''";
//-----custom filters-------
if ( $("#select_type").val() != "") {
whereClause += " AND 'Category' = '" + $("#select_type").val() + "'";
}
if ( $("#select_type1").val() != "") {
whereClause += " AND 'sex' = '" + $("#select_type1").val() + "'";
}
if ( $("#select_type2").val() != "") {
whereClause += " AND 'Subindustry' = '" + $("#select_type2").val() + "'";
}
//-------end of custom filters--------
if (address != "") {
if (address.toLowerCase().indexOf(MapsLib.locationScope) == -1)
address = address + " " + MapsLib.locationScope;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
MapsLib.currentPinpoint = results[0].geometry.location;
$.address.parameter('address', encodeURIComponent(address));
$.address.parameter('radius', encodeURIComponent(MapsLib.searchRadius));
map.setCenter(MapsLib.currentPinpoint);
map.setZoom(14);
if (MapsLib.searchRadius == "400")
map.setZoom(16);
else if (MapsLib.searchRadius == "805")
map.setZoom(15);
else if (MapsLib.searchRadius == "1610")
map.setZoom(14);
else if (MapsLib.searchRadius == "3220")
map.setZoom(13);
else if (MapsLib.searchRadius == "8050")
map.setZoom(12);
else if (MapsLib.searchRadius == "16100")
map.setZoom(11);
else if (MapsLib.searchRadius == "40250")
map.setZoom(09);
else if (MapsLib.searchRadius == "80500")
map.setZoom(08);
else if (MapsLib.searchRadius == "161000")
map.setZoom(07);
else if (MapsLib.searchRadius == "402500")
map.setZoom(06);
else if (MapsLib.searchRadius == "805000")
map.setZoom(05);
else if (MapsLib.searchRadius == "1610000")
map.setZoom(04);
else
map.setZoom(14);
MapsLib.addrMarker = new google.maps.Marker({
position: MapsLib.currentPinpoint,
map: map,
icon: MapsLib.addrMarkerImage,
animation: google.maps.Animation.DROP,
title:address
});
whereClause += " AND ST_INTERSECTS(" + MapsLib.locationColumn + ", CIRCLE(LATLNG" + MapsLib.currentPinpoint.toString() + "," + MapsLib.searchRadius + "))";
MapsLib.drawSearchRadiusCircle(MapsLib.currentPinpoint);
MapsLib.submitSearch(whereClause, map, MapsLib.currentPinpoint);
}
else {
alert("We could not find your address: " + status);
}
});
}
else { //search without geocoding callback
MapsLib.submitSearch(whereClause, map);
}
},
submitSearch: function(whereClause, map, location) {
//get using all filters
//NOTE: styleId and templateId are recently added attributes to load custom marker styles and info windows
//you can find your Ids inside the link generated by the 'Publish' option in Fusion Tables
//for more details, see https://developers.google.com/fusiontables/docs/v1/using#WorkingStyles
MapsLib.searchrecords = new google.maps.FusionTablesLayer({
query: {
from: MapsLib.fusionTableId,
select: MapsLib.locationColumn,
where: whereClause
},
styleId: 2,
templateId: 2
});
MapsLib.searchrecords.setMap(map);
MapsLib.getCount(whereClause);
MapsLib.getList(whereClause);
},
clearSearch: function() {
if (MapsLib.searchrecords != null)
MapsLib.searchrecords.setMap(null);
if (MapsLib.addrMarker != null)
MapsLib.addrMarker.setMap(null);
if (MapsLib.searchRadiusCircle != null)
MapsLib.searchRadiusCircle.setMap(null);
},
findMe: function() {
// Try W3C Geolocation (Preferred)
var foundLocation;
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
foundLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
MapsLib.addrFromLatLng(foundLocation);
}, null);
}
else {
alert("Sorry, we could not find your location.");
}
},
addrFromLatLng: function(latLngPoint) {
geocoder.geocode({'latLng': latLngPoint}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
$('#search_address').val(results[1].formatted_address);
$('.hint').focus();
MapsLib.doSearch();
}
} else {
alert("Geocoder failed due to: " + status);
}
});
},
drawSearchRadiusCircle: function(point) {
var circleOptions = {
strokeColor: "#4b58a6",
strokeOpacity: 0.3,
strokeWeight: 1,
fillColor: "#4b58a6",
fillOpacity: 0.05,
map: map,
center: point,
clickable: false,
zIndex: -1,
radius: parseInt(MapsLib.searchRadius)
};
MapsLib.searchRadiusCircle = new google.maps.Circle(circleOptions);
},
query: function(selectColumns, whereClause, callback) {
var queryStr = [];
queryStr.push("SELECT " + selectColumns);
queryStr.push(" FROM " + MapsLib.fusionTableId);
queryStr.push(" WHERE " + whereClause);
var sql = encodeURIComponent(queryStr.join(" "));
$.ajax({url: "https://www.googleapis.com/fusiontables/v1/query?sql="+sql+"&callback="+callback+"&key="+MapsLib.googleApiKey, dataType: "jsonp"});
},
handleError: function(json) {
if (json["error"] != undefined) {
var error = json["error"]["errors"]
console.log("Error in Fusion Table call!");
for (var row in error) {
console.log(" Domain: " + error[row]["domain"]);
console.log(" Reason: " + error[row]["reason"]);
console.log(" Message: " + error[row]["message"]);
}
}
},
getCount: function(whereClause) {
var selectColumns = "Count()";
MapsLib.query(selectColumns, whereClause,"MapsLib.displaySearchCount");
},
displaySearchCount: function(json) {
MapsLib.handleError(json);
var numRows = 0;
if (json["rows"] != null)
numRows = json["rows"][0];
var name = MapsLib.recordNamePlural;
if (numRows == 1)
name = MapsLib.recordName;
$( "#result_count" ).fadeOut(function() {
$( "#result_count" ).html(MapsLib.addCommas(numRows) + " " + name + " found");
});
$( "#result_count" ).fadeIn();
},
getList: function(whereClause) {
var selectColumns = "StoreName, Address, Contact, Website";
MapsLib.query(selectColumns, whereClause, "MapsLib.displayList");
},
displayList: function(json) {
MapsLib.handleError(json);
var data = json["rows"];
var template = "";
var results = $("#results_list");
results.hide().empty(); //hide the existing list and empty it out first
if (data == null) {
//clear results list
results.append("<li><span class='lead'>No results found</span></li>");
}
else {
for (var row in data) {
template = "\
<div class='row-fluid item-list'>\
<div class='span12'>\
<span class='lead'>" + data[row][0] + "\</span>\
<br />\
" + data[row][4] + "\
<br />\
" + data[row][5] + "\
<br />\
<a href='" + data[row][6] + "'>\
<span>" + data[row][7] + "\</span>\
</a>\
<br />\
<a onClick=''>\
<span style='color: red;'>See on Map</span>\
</a>\
</div>\
</div>"
results.append(template);
}
}
results.fadeIn();
},
addCommas: function(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
},
// maintains map centerpoint for responsive design
calculateCenter: function() {
center = map.getCenter();
},
//converts a slug or query string in to readable text
convertToPlainString: function(text) {
if (text == undefined) return '';
return decodeURIComponent(text);
}
//-----custom functions-------
// NOTE: if you add custom functions, make sure to append each one with a comma, except for the last one.
// This also applies to the convertToPlainString function above
//-----end of custom functions-------
}

it's not as easy as it seems.
The location of a feature(e.g. marker) on a FusionTableLayer isn't available until you really click on it(this click can't be simulated).
You can't get the LatLng of the feature with the query, because you've stored addresses and not LatLng's inside the FusionTable.
Although the API knows the LatLng's of the addresses, there is no way to access them.
So the only thing you may do is:
Take the address of the row
use google.maps.Geocoder to geocode this address
open a custom InfoWindow(content populated by the properties of the row) at the LatLng returned by the geocoder.

I'd rather add a comment to Dr.Molle's answer, but thanks to Stack Overflow's point system, I have to add an answer even though I don't think this will be truly useful because I can't be very specific. I'm assuming that's because the goal is to get me to answer questions, not just talk about answers ;)
Dr.Molle was on the right track, but invoking the geocoder on every click is not only painfully slow, but every IP only gets so many geocoder requests per day. So:
Create a column that has a unique identifier. Add a listener to the marker so that when clicked, it will query your table for that ID. When the results come in, create an InfoWindow (sorry, no help here) with the returned data.
Here's a sample that does exactly what you're asking for:
https://developers.google.com/fusiontables/docs/samples/change_infowindow_content

Related

google maps directionsService giving wrong results

I am trying to get distance in miles and estimated time with googles directionsService. It sort of works but I know the results its giving me are incorrect. The distance and time are too short? I need results in driving mode. A sample of the code is :
HTML
<input id="s_lat" value="52.441334" />
<input id="s_lng" value="-1.654737" />
<input id="d_lat" value="52.450439" />
<input id="d_lng" value="-1.729660" />
JS
var n_start = s_lat + ',' + s_lng;
var n_end = d_lat + ',' + d_lng;
function getdistance() {
var directionsService = new google.maps.DirectionsService();
var request = {
origin : n_start,
destination : n_end,
travelMode : google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
durationInTraffic: true
};
directionsService.route(request, function(response, status) {
if ( status == google.maps.DirectionsStatus.OK ) {
alert (response.routes[0].legs[0].duration.value);
alert (response.routes[0].legs[0].distance.value);
}
else {
// oops, there's no route between these two locations
}
});
}
The result I get with the posted code is NOT_FOUND, I don't get a distance. A comma separated string is not a google.maps.LatLng or a google.maps.LatLngLiteral, it is treated as an address and geocoded before returning the results.
This:
var n_start = s_lat + ',' + s_lng;
var n_end = d_lat + ',' + d_lng;
Should be (google.maps.LatLngLiteral):
var n_start = {lat: parseFloat(s_lat.value), lng: parseFloat(s_lng.value)};
var n_end = {lat: parseFloat(d_lat.value), lng: parseFloat(d_lng.value)};
Or (google.maps.LatLng):
var n_start = new google.maps.LatLng(s_lat.value,s_lng.value);
var n_end = new google.maps.LatLng(d_lat.value,d_lng.value);
Proof of concept fiddle
Code snippet:
function initMap() {
var n_start = new google.maps.LatLng(s_lat.value,s_lng.value);
var n_end = new google.maps.LatLng(d_lat.value,d_lng.value);
function getdistance() {
var directionsService = new google.maps.DirectionsService();
var request = {
origin: n_start,
destination: n_end,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
durationInTraffic: true
};
console.log(JSON.stringify(request));
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
console.log("duration=" + response.routes[0].legs[0].duration.value + " seconds");
console.log("distance=" + response.routes[0].legs[0].distance.value + " meters");
document.getElementById('result').innerHTML = "distance=" + (response.routes[0].legs[0].distance.value / 1000).toFixed(2) + " km<br>duration=" + (response.routes[0].legs[0].duration.value / 60).toFixed(2) + " minutes";
new google.maps.DirectionsRenderer({
map: new google.maps.Map(document.getElementById('map')),
directions: response
})
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
getdistance();
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<input id="s_lat" value="52.441334" />
<input id="s_lng" value="-1.654737" />
<input id="d_lat" value="52.450439" />
<input id="d_lng" value="-1.729660" /><br>
<div id="result"></div>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>

Google maps API, waypoints, stopover true/false option give different results when using departureTime for specific open(summer)/closed(winter) roads

When following Google API Directions i ran into a problem. I cannot find a solution to get this working correctly. Seems like it has to be a google issue.
If you check the images and snippet example you can see between waypoint A end B there is a road that is only open during summertime. During wintertime closed and gets a longer route which is normal.
When stopover is set to FALSE (during summertime) then the route is correct but there are no legs anymore. I need those legs between the waypoints. When triple checking the google API i cannot find why this behavior occurs. I'm aware some things are not working with TRANSIT but this is not the case here.
So i need the SHORT summer route with stopovers and with leg information as result. Any ideas to get this?
Image: stopover=false
Image: stopover=true
When switching between stopover mode change 2 vars at line 36-37
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3";></script>
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var wptruefalse;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var first = new google.maps.LatLng(61.84448683734486, 8.85223388671875);
var second = new google.maps.LatLng(61.75298123367897, 9.078826904296875);
var start = new google.maps.LatLng(61.484039,7.645798);
var end = new google.maps.LatLng(61.944118091023746,7.97882080078125);
var request = {
origin: start,
destination: end,
waypoints: [{location: first, stopover: wptruefalse},
{location: second, stopover: wptruefalse}],
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
drivingOptions: {
departureTime: new Date("08/08/2018")
},
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById("directions_panel");
summaryPanel.innerHTML = "";
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
summaryPanel.innerHTML += route.legs[i].start_address + " to ";
summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
summaryPanel.innerHTML += route.legs[i].distance.text + "<br /><br />";
}
} else {
alert("directions response " + status);
}
});
}
function doClick(myRadio) {
if (myRadio.value === "true") {
wptruefalse = true;
} else {
wptruefalse = false;
}
calcRoute();
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="float:left;width:70%;height:100%;"></div>
<div id="control_panel" style="float:right;width:30%;text-align:left;padding-top:20px">
API Key is needed to test properly
<form>
<input type="radio" name="wpradio" onclick="doClick(this);" value="true" checked> True
<input type="radio" name="wpradio" onclick="doClick(this);" value="false"> False
</form>
<div id="directions_panel" style="margin:20px;background-color:#FFEE77;"></div>
</div>
</body>
</html>
Thanks in advance!

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;
}
});
});

Raising an exception for a grey streetview location in Google Maps JavaScript API v3

Look, I'm using Google Maps JavaScript API v3. The user fills in an address and I show the streetview of that address. Everything's fine (a lot of locations work perfectly), till a enter a location like "Laken". It just displays grey, nothing else. I want to prevent the user from continuing to the next page with a grey image instead of a google maps streetview.
When I fill in Laken, the getPanoramaByLocation() function returns status == "OK", because it has found something, but its not a visible image, it's just grey. How can I prevent the API from doing this? Something like, when you can't display this location(is grey), display the next available location nearby.
Here's an extract from the code:
Function:
<script type="text/javascript">
//this is a standard location that I show when te user starts
var map;
var huis_lat,huis_lng;
$(document).ready(function(){
map = new GMaps({
el: '#map',
lat: -12.043333,
lng: -77.028333
});
//SAVE HOMELAT&LONGT
$('#geocoding_form').submit(function(e){
var address=document.getElementById("address").value;
e.preventDefault();
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status)
{
if(status=='OK'){
var latlng = results[0].geometry.location;
huis_lat=latlng.lat();
huis_lng=latlng.lng();
verander(huis_lat, huis_lng);
document.getElementById("div_overlayStart").style.display="none";
document.getElementById("div_overlayThuis").style.display="block";
}
else if(!address) //no address
{
alert("fout?")
document.getElementById('alarm1').innerHTML = 'FILL IN ADDRESS';
}
else if(status=='UNKNOWN_ERROR')
{
document.getElementById('alarm1').innerHTML = 'UNKNOWN ERROR!';
}
else if(status=='ZERO_RESULTS')
{
document.getElementById('alarm1').innerHTML = 'UNKNOWN ADDRESS!';
}
}
});
});
});
</script>
HTML:
EX: Fill in: Kongingslaan 1, Laken
<body>
<form method="post" id="geocoding_form">
<div class="input">
<input type="text" id="address" name="address" />
<button type="submit" class="linksSocial" style="border: 0; background: transparent">
<img src="images/btn_job.png" width="231" heght="36" alt="submit" />
</button>
</div>
</form>
</body>
Function verander():
<script type="text/javascript">
function verander(google_lat, google_lng) {
var bryantPark = new google.maps.LatLng(google_lat, google_lng);
var panoramaOptions = {
position:bryantPark,
pov: {
heading: 185,
pitch:0,
zoom:1,
},
panControl : false,
streetViewControl : false,
mapTypeControl: false,
overviewMapControl: false ,
linksControl: false,
addressControl:false,
zoomControl : false,
}
map = new google.maps.StreetViewPanorama(document.getElementById("map_canvas"), panoramaOptions);
map.setVisible(true);
}
</script>
Use google.maps.StreetViewService.getPanoramaByLocation() to determine if there is a panorama available for the given location.
Quick and dirty solution. I noticed resizing the Window worked for me on this problem. And it also worked if you fire the event via js.
window.dispatchEvent(new Event('resize'));
Try this :
$(document).ready(function(){
var map = new GMaps({
el: '#map',
lat: -12.043333,
lng: -77.028333
});
//SAVE HOMELAT&LONGT
$('#geocoding_form').submit(function(e) {
e.preventDefault();
var address = $('#address').val().trim();
if(!address.length) {
$('#alarm1').html('Fill in your address!');
}
GMaps.geocode({
address: address,
callback: function(results, status) {
if(status !== 'OK' || results.length == 0) {
$("#div_overlayStart").show();
$("#div_overlayThuis").hide();
}
if(status !== 'OK') {
$('#alarm1').text('Something went wrong!');
}
else if(results.length == 0) {
$('#alarm1').html('No results found!');
}
else {
$('#alarm1').text('');
var latlng = results[0].geometry.location;
verander(latlng.lat(), latlng.lng());
$("#div_overlayStart").hide();
$("#div_overlayThuis").show();
}
}
});
});
});
I also had problems with StreetView displaying 'grey' at some locations.
I don't like the solution given here.
Have a look at my solution in another post, which is also to do with StreetView being displayed 'grey' at some locations -->
Google maps streetview tiles do not load in Firefox initially, only after dragging
This solves the problem:
<script type="text/javascript">
var map;
var huis_lat,huis_lng;
var richting = 0;
$(document).ready(function(){
map = new GMaps({
el: '#map',
lat: -12.043333,
lng: -77.028333
});
//SAVE HOMELONG/LAT IN VAR
$('#geocoding_form').submit(function(e){
var address=document.getElementById("address").value;
/* STATUS
OK The request was successful.
UNKNOWN_ERROR The request could not be successfully processed, yet the exact reason for failure is unknown.
ZERO_RESULTS There are no nearby panoramas.
*/
//CHECK IF ADDRESS IS VALID (IS THEIR A VALID X/Y COORDINATE FOR IT?)
e.preventDefault();
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status)
{
if(status=='OK'){
var latlng = results[richting].geometry.location;
huis_lat=latlng.lat();
huis_lng=latlng.lng();
verander(huis_lat, huis_lng);
document.getElementById("div_overlayStart").style.display="none";
document.getElementById("div_overlayThuis").style.display="block";
}
else if(!address) //no address
{
document.getElementById('alarm1').innerHTML = 'Gelieve u adres in te vullen!';
}
else if(status=='UNKNOWN_ERROR')
{
document.getElementById('alarm1').innerHTML = 'Er ging iets mis (onbekende fout)!';
}
else if(status=='ZERO_RESULTS')
{
document.getElementById('alarm1').innerHTML = 'Er is van deze locatie geen streetview beschikbaar!';
}
}
});
});
});
//+1 one for the array results[richting].geometry.location
function verhoog(){
var address=document.getElementById("address").value;
richting++;
//e.preventDefault();
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status)
{
if(status=='OK'){
var latlng = results[richting].geometry.location;
huis_lat=latlng.lat();
huis_lng=latlng.lng();
verander(huis_lat, huis_lng);
document.getElementById("div_overlayStart").style.display="none";
document.getElementById("div_overlayThuis").style.display="block";
}
}
});
}
</script>
Check if the panorama (streetview) for these X/Y coordinates is visible (not grey). I use the function getPanoramaByLocation to determine this. This returns a status like the previous one. If there are ZERO_RESULTS (=grey zone) it activates the function verhoog() that increments the array of results by 1.
<script type="text/javascript">
var map;
function verander(google_lat, google_lng) {
var bryantPark = new google.maps.LatLng(google_lat, google_lng);
//CHECK FOR GREY ZONE
var client = new google.maps.StreetViewService();
client.getPanoramaByLocation(bryantPark, 50, function(result, status) {
if (status == "ZERO_RESULTS") {
verhoog();
}
else if(status == "OK")
{
var panoramaOptions =
{
position:bryantPark,
pov: {
heading: 185,
pitch:0,
zoom:1,
},
panControl : false,
streetViewControl : false,
mapTypeControl: false,
overviewMapControl: false ,
linksControl: false,
addressControl:false,
zoomControl : false,
}
map = new google.maps.StreetViewPanorama(document.getElementById("map_canvas"), panoramaOptions);
map.setVisible(true);
}
else if(status=='UNKNOWN_ERROR')
{
alert("Er ging iets mis");
}
});
}
</script>

fusion table issues with onClick and custom icons

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

Resources