select st_distance as 'distance' not working in google fusion table - google-maps

ST_DISTANCE AS 'distance' not working on below code:
var query = "SELECT 'Coordinates' as 'Coordinates', " +
"'Lender_Name' as 'Lender_Name', " +
"'ZIP_Code' as 'ZIP_Code' , " +
"ST_DISTANCE('Coordinates', 'LATLNG(" + lat + " " + long + ")') AS 'distance' " +
" FROM " + tableid + " ORDER BY ST_DISTANCE(Coordinates, LATLNG(" + lat + "," + long + ")) LIMIT 5";
When I am using without ST_DISTANCE as distance it's working fine for me:
var query = "SELECT 'Coordinates' as 'Coordinates', " +
"'Lender_Name' as 'Lender_Name', " +
"'ZIP_Code' as 'ZIP_Code' " +
" FROM " + tableid + " ORDER BY ST_DISTANCE(Coordinates, LATLNG(" + lat + "," + long + ")) LIMIT 5";
Can Any one help me how can i get st_distance in a alias?

I have achieved the solution by the following code.
function initialize() {
//CONVERT THE MAP DIV TO A FULLY-FUNCTIONAL GOOGLE MAP
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var output = '<tr><th scope="col">From</th><th scope="col">To</th><th scope="col">Miles</th></tr>';
var currZipCode = 99929;
currZipCode = currZipCode.toString();
var destinationZipCode = 99803;
destinationZipCode = destinationZipCode.toString();
calcMileage();
function calcMileage() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [ currZipCode ],
destinations: [ destinationZipCode ],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL
}, function(response, status) {
if(status == google.maps.DistanceMatrixStatus.OK) {
var tempDistance = response.rows[0].elements[0].distance.text;
} else {
var tempDistance = 'ERROR';
}
//STORE CURRENT OUTPUT AND GET THE NEXT DESTINATION
output += '<tr><td>' + currZipCode + '</td><td>' + destinationZipCode + '</td><td>' + tempDistance + '</td></tr>';
displayResults();
}
);
function displayResults() {
document.getElementById('zip_code_output').innerHTML = '<table cellpadding="5">' + output + '</table>';
}
}
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
}
//START THE SCRIPT (AFTER THE PAGE LOADS)
window.onload = loadScript;

Related

maps markers with input sliders

Let me explain the project a bit. i have a huge list of stores with addresses (longitude and latitude and code client ....).
Now, my problem is, i must be able to filter these markers depending on CodeClient i mean to find the client in google maps based on CodeClient .
The implementation is similar to the answer I mentioned before. You should add an input for code of client and a search button. In the function where you create markers add a property 'code' for each marker marker.code = CodeClient;. When you click search button it executes the filterByCode() function. If you pass empty value it restores all markers.
Have a look at modified code
// necessary variables
var map;
var infoWindow;
var markersData = [];
var markerCluster;
var markerArray = []; //create a global array to store markers
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(32, -6),
zoom: 7,
mapTypeId: 'roadmap',
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// create MarkerClusterer, markersArray is not populated yet
markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
// a new Info Window is created
infoWindow = new google.maps.InfoWindow();
// Event that closes the Info Window with a click on the map
google.maps.event.addListener(map, 'click', function() {
infoWindow.close();
});
// Finally displayMarkers() function is called to begin the markers creation
displayMarkers();
}
google.maps.event.addDomListener(window, 'load', initialize);
// This function will iterate over markersData array
// creating markers with createMarker function
function displayMarkers() {
// this variable sets the map bounds according to markers position
var bounds = new google.maps.LatLngBounds();
// for loop traverses markersData array calling createMarker function for each marker
$.get("https://gist.githubusercontent.com/abdelhakimsalama/358669eda44d8d221bf58c629402c40b/raw/bae93c852669a35f0e7053e9f8d068841ddf146a/get_data_google_api", function(response) {
markersData = JSON.parse(response);
for (var i = 0; i < markersData.length; i++) {
var latlng = new google.maps.LatLng(markersData[i].Latitude, markersData[i].Longitude);
var Route = markersData[i].Route;
var Secteur = markersData[i].Secteur;
var Agence = markersData[i].Agence;
var CodeClient = markersData[i].CodeClient;
var PrecisionGPS = markersData[i].PrecisionGPS;
var Latitude = markersData[i].Latitude;
var Longitude = markersData[i].Longitude;
var BarCode = markersData[i].BarCode;
var PrenomClient = markersData[i].PrenomClient;
var NumAdresse = markersData[i].NumAdresse;
var Tel = markersData[i].Tel;
var Whatsapp = markersData[i].Whatsapp;
var NbrFrigo = markersData[i].NbrFrigo;
var OpenAm = markersData[i].OpenAm;
var CloseAm = markersData[i].CloseAm;
var OpenPm = markersData[i].OpenPm;
var ClosePm = markersData[i].ClosePm;
var OpenAmVen = markersData[i].OpenAmVen;
var CloseAmVen = markersData[i].CloseAmVen;
var OpenPmVen = markersData[i].OpenPmVen;
var ClosePmVen = markersData[i].ClosePmVen;
var OpenAmDim = markersData[i].OpenAmDim;
var CloseAmDim = markersData[i].CloseAmDim;
var OpenPmDim = markersData[i].OpenPmDim;
var ClosePmDim = markersData[i].ClosePmDim;
var IMEI = markersData[i].IMEI;
var Date_Added = markersData[i].Date_Added;
createMarker(latlng, Route, Agence, Secteur, CodeClient, PrecisionGPS, Latitude, Longitude, BarCode, PrenomClient, NumAdresse, Tel, Whatsapp, NbrFrigo, OpenAm, CloseAm, OpenPm, ClosePm, OpenAmVen, CloseAmVen, OpenPmVen, ClosePmVen, OpenAmDim, CloseAmDim, OpenPmDim, ClosePmDim, IMEI, Date_Added);
// marker position is added to bounds variable
bounds.extend(latlng);
}
// Finally the bounds variable is used to set the map bounds
// with fitBounds() function
map.fitBounds(bounds);
});
}
// This function creates each marker and it sets their Info Window content
function createMarker(latlng, Route, Agence, Secteur, CodeClient, PrecisionGPS, Latitude, Longitude, BarCode, PrenomClient, NumAdresse, Tel, Whatsapp, NbrFrigo, OpenAm, CloseAm, OpenPm, ClosePm, OpenAmVen, CloseAmVen, OpenPmVen, ClosePmVen, OpenAmDim, CloseAmDim, OpenPmDim, ClosePmDim, IMEI, Date_Added) {
var marker = new google.maps.Marker({
map: map,
position: latlng,
title: CodeClient
});
marker.code = CodeClient;
markerArray.push(marker); //push local var marker into global array
// add marker to the MarkerClusterer
markerCluster.addMarker(marker);
// This event expects a click on a marker
// When this event is fired the Info Window content is created
// and the Info Window is opened.
google.maps.event.addListener(marker, 'click', function() {
var dicoFrigosDetails = {};
var HTMLtext = "";
for (var i = 1; i <= Object.keys(dicoFrigosDetails).length / 4; i++) {
HTMLtext += '';
}
// Creating the content to be inserted in the infowindow
var iwContent = '<div id="iw_container">' +
'<div class="iw_title">Code Client : ' + CodeClient +
'</div>' + '<div class="iw_content">Précision : ' + PrecisionGPS +
'<br />Latitude : ' + Latitude +
'<br />Longitude : ' + Longitude +
'<br />Route : ' + Route +
'<br />Secteur : ' + Secteur +
'<br />Agence : ' + Agence +
'<br />Code-barres : ' + BarCode +
'<br />prenom de Client : ' + PrenomClient +
//'<br />nom Complet de Client : ' + PrenomClient + ' ' + NomClient +
'<br />Num Adresse : ' + NumAdresse +
'<br />Téléphone : ' + Tel +
'<br />Whatsapp : ' + Whatsapp +
'<br />Nbr Frigos : ' + NbrFrigo + HTMLtext +
'<br />Ouverture Matin : ' + OpenAm +
'<br />Fermeture Matin : ' + CloseAm +
'<br />Ouverture après-midi : ' + OpenPm +
'<br />Fermeture Après-midi : ' + ClosePm +
'<br />Ouverture Matin Ven : ' + OpenAmVen +
'<br />Fermeture Matin Ven : ' + CloseAmVen +
'<br />Ouverture après-midi Ven: ' + OpenPmVen +
'<br />Fermeture après-midi Ven: ' + ClosePmVen +
'<br />Ouverture Matin Dim : ' + OpenAmDim +
'<br />Fermeture Matin Dim : ' + CloseAmDim +
'<br />Ouverture après-midi Dim : ' + OpenPmDim +
'<br />Fermeture après-midi Dim : ' + ClosePmDim +
'<br />IMEI : ' + IMEI +
'<br />Date Passage : ' + Date_Added +
'</div>';
// including content to the Info Window.
infoWindow.setContent(iwContent);
// opening the Info Window in the current map and at the current marker location.
infoWindow.open(map, marker);
});
}
function filterByCode() {
var code = document.getElementById("code-client").value;
var bounds = new google.maps.LatLngBounds();
markerCluster.clearMarkers();
if (code) {
markerArray.forEach(function(marker) {
marker.setMap(null);
});
var filtered = markerArray.filter(function(marker) {
return marker.code === code;
});
if (filtered && filtered.length) {
filtered.forEach(function(marker) {
bounds.extend(marker.getPosition());
marker.setMap(map);
});
markerCluster.addMarkers(filtered);
markerCluster.redraw();
map.fitBounds(bounds);
}
} else {
markerArray.forEach(function(marker) {
bounds.extend(marker.getPosition());
marker.setMap(map);
});
markerCluster.addMarkers(markerArray);
markerCluster.redraw();
map.fitBounds(bounds);
}
}
html {
height: 100%;
background: gray;
}
body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas {
height: 100%;
}
#iw_container .iw_title {
font-size: 16px;
font-weight: bold;
}
.iw_content {
padding: 15px 15px 15px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>InnoTech - Map - Server</title>
<meta charset="utf-8">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript" src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<div id="search-code-container">
<input id="code-client" title="Enter code" type="text" placeholder="Enter code (E.g. 511557)" value=""/>
<input id="code-client-btn" type="button" value="Search" onclick="filterByCode()" />
</div>
<div id="map-canvas" />
I hope this helps!

How to pass location and radius in google map API?

My goal is to get list of zip codes by passing parameter of location and radius of particular limit.
I got only the location, but I couldn't get the radius of certain zipcode.
https://maps.googleapis.com/maps/api/elevation/json?locations=7034&key=YOUR_API_KEY
How can I get the list of zipcode in certain radius ?
Please guide me to solve this issue
You need a database that contains data about the zipcodes. Here is an example that uses a FusionTable containing US zip codes:
http://www.geocodezip.com/geoxml3_test/v3_FusionTables_zipcodeInRadius.html
code snippet:
google.load('visualization', '1', {
'packages': ['corechart', 'table', 'geomap']
});
var map;
var labels = [];
var layer;
var tableid = "1VFp4XJEdnR769R2CFRghlmDpUd15dQArpwzcBBs"; //1499916;
var circle;
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: new google.maps.LatLng(37.23032838760389, -118.65234375),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
layer = new google.maps.FusionTablesLayer({
query: {
from: tableid,
select: "geometry"
}
});
// layer.setQuery("SELECT 'geometry' FROM " + tableid);
layer.setMap(map);
codeAddress();
}
function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
if (results[0].geometry.viewport)
map.fitBounds(results[0].geometry.viewport);
var latLng = results[0].geometry.location;
var radius = parseFloat(document.getElementById('radius').value) * 1609.34;
if (isNaN(radius)) radius = 5 * 1609.34; // default to 5 miles
displayZips(results[0].geometry.location, radius);
if (circle && circle.setMap) {
circle.setMap(null);
}
circle = new google.maps.Circle({
center: latLng,
radius: radius,
map: map
});
layer.setQuery({
select: 'geometry',
from: tableid,
where: "ST_INTERSECTS(geometry, CIRCLE(LATLNG(" + latLng.toUrlValue(6) + ")," + radius.toFixed(2) + "))"
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function displayZips(latLng, radius) {
var queryStr = "SELECT geometry, ZIP, latitude, longitude FROM " + tableid + " WHERE ST_INTERSECTS(geometry, CIRCLE(LATLNG(" + latLng.toUrlValue(6) + ")," + radius.toFixed(2) + "))";
var queryText = encodeURIComponent(queryStr);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(displayZipText);
}
var infowindow = new google.maps.InfoWindow();
function displayZipText(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
if (map.getZoom() < 11) return;
FTresponse = response;
//for more information on the response object, see the documentation
//http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
var zipsList = "";
for (i = 0; i < numRows; i++) {
var zip = response.getDataTable().getValue(i, 1);
var zipStr = zip.toString()
while (zipStr.length < 5) {
zipStr = '0' + zipStr;
}
zipsList += zipStr + " ";
var point = new google.maps.LatLng(
parseFloat(response.getDataTable().getValue(i, 2)),
parseFloat(response.getDataTable().getValue(i, 3)));
}
document.getElementById('zips').innerHTML = "zipcodes in radius=" + zipsList;
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
width: 100%;
height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="http://www.google.com/jsapi"></script>
<form>
<span class="style51"><span class="style49">Show</span>:</span>
<label>Address:</label><input id="address" type="text" value="07646" /><label>Radius:</label><input id="radius" type="text" value="0.5" />
<input id="geocode" type="button" onclick="codeAddress();" value="Geocode" />
</form>
<div id="zips"></div>
<div id="map_canvas"></div>

How to show marker on map & show item on html tables using textbox? (google maps v3)

I am using this JSON(WebAPI) to view google markers on map - http://track.asiacom.co.th/fmswebapi/api/assetinfo.
I want to filter/search the markers by using html textbox. Upon searching, it will display the marker/s on map and it will also display the item/searched marker on html table at the same time. Pls. help how to achieved this?
Sample HTML
<div id="page-content"><div id="map-canvas"></div></div><table id="assetStatus" class="table table-condensed table-vcenter searchable" data-flat="true" data-click-to-select="true" data-show-header="false" data-search="false" data-show-refresh="false" data-show-toggle="false" data-show-columns="false" data-sort-name="id" data-page-list="[10, 20, 50, 100]" data-page-size="5" data-pagination="false" data-show-pagination-switch="false">/table>
Sample Javascript
function initialize() {
var geocoder;
var map;
var markers = new Array();
var marker;
var assets = [];
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(13.7500, 100.4833);
var mapTypeIds = ["SEA"];
for (var type in google.maps.MapTypeId) {
mapTypeIds.push(google.maps.MapTypeId[type]);
}
var mapOptions = {
zoom: 12,
center: latlng,
panControl: false,
zoomControl: false,
mapTypeControl: true,
//mapTypeId: "",
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
//style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
mapTypeIds: mapTypeIds,
position: google.maps.ControlPosition.TOP_LEFT
},
streetViewControl: true,
streetViewControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT
},
scaleControl: true,
overviewMapControl: true
}
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
resize('map-canvas', 32);
// handle window resize
function resize(element, offset) {
// get window height
var height = 0;
if (typeof (window.innerWidth) == 'number') height = window.innerHeight;
else if (document.documentElement && document.documentElement.clientHeight)
height = document.documentElement.clientHeight;
else if (document.body && document.bodyclientHeight)
height = document.body.clientHeight;
else if (screen.availheight)
height = screen.availheight;
else return;
// update window size
height = height - offset;
if (height > 0)
document.getElementById(element).style.height = height + "px";
}
//Transit Layer - off
//Start
/*=================================================*/
//var transitLayer = new google.maps.TransitLayer();
//transitLayer.setMap(map);
/*=================================================*/
//End
//Traffic Layer - On
//Start
/*=================================================*/
var controlDiv = document.createElement('DIV');
$(controlDiv).addClass('gmap-control-container')
.addClass('gmnoprint');
var controlUI = document.createElement('DIV');
$(controlUI).addClass('gmap-control');
$(controlUI).text('Traffic');
$(controlDiv).append(controlUI);
var legend = '<ul>'
+ '<li><span style="background-color: #30ac3e"> </span><span style="color: #30ac3e"> > Smooth Traffic</span></li>'
+ '<li><span style="background-color: #ffcf00"> </span><span style="color: #ffcf00"> Slow Moving Traffic</span></li>'
+ '<li><span style="background-color: #ff0000"> </span><span style="color: #ff0000"> < Heavy Traffic</span></li>'
+ '<li><span style="background-color: #c0c0c0"> </span><span style="color: #c0c0c0"> No data available</span></li>'
+ '</ul>';
var controlLegend = document.createElement('DIV');
$(controlLegend).addClass('gmap-control-legend');
$(controlLegend).html(legend);
$(controlLegend).hide();
$(controlDiv).append(controlLegend);
// Set hover toggle event
$(controlUI)
.mouseenter(function () {
$(controlLegend).show();
})
.mouseleave(function () {
$(controlLegend).hide();
});
var trafficLayer = new google.maps.TrafficLayer();
google.maps.event.addDomListener(controlUI, 'click', function () {
if (typeof trafficLayer.getMap() == 'undefined' || trafficLayer.getMap() === null) {
$(controlUI).addClass('gmap-control-active');
trafficLayer.setMap(map);
} else {
trafficLayer.setMap(null);
$(controlUI).removeClass('gmap-control-active');
}
});
map.controls[google.maps.ControlPosition.TOP_LEFT].push(controlDiv);
//Traffic Layer - On
//End
/*=================================================*/
//SEA Layer - On
/*=================================================*/
//Start
map.mapTypes.set("SEA", new google.maps.ImageMapType({
getTileUrl: function (coord, zoom) {
return "http://a.tile.osm-tools.org/osm_then/" + zoom + "/" + coord.x + "/" + coord.y + ".png";
},
tileSize: new google.maps.Size(256, 256),
name: "Multilanguage",
alt: "Show Standard",
maxZoom: 20
}));
//End
/*=================================================*/
setMarkers(map, assets);
google.maps.event.addListener(map, 'mousemove', function (event) {
document.getElementById('panel').innerHTML =
event.latLng.lat() + ', ' + event.latLng.lng();
});
}
function setMarkers(map, assets) {
// Add markers to the map
// Shapes define the clickable region of the icon.
// The type defines an HTML <area> element 'poly' which
// traces out a polygon as a series of X,Y points. The final
// coordinate closes the poly by connecting to the first
// coordinate.
var shape = {
coords: [1, 1, 1, 20, 18, 20, 18, 1],
type: 'poly'
};
var url = 'http://track.asiacom.co.th/fmswebapi/api/assetinfo';
$.getJSON(url, function (assets) {
for (var i = 0; i < assets.length; i++) {
var asset = assets[i];
var category = asset.Category;
var engine = asset.LastPos.Engine;
var company = asset.Company;
var vechs = asset.Name;
if (assets.indexOf(i) !== -1) continue;
var myLatLng = new google.maps.LatLng(parseFloat(asset.LastPos.PosY), parseFloat(asset.LastPos.PosX));
//Background marker
var icon = "";
switch (asset.LastPos.Engine) {
case "MOVE":
icon = "move";
break;
case "IDLE":
icon = "idle";
break;
case "STOP":
icon = "stop";
break;
}
icon = "http://track.asiacom.co.th/track/Dashboard/img/" + icon + ".png";
// Category image
var markerCategory = "";
switch (asset.Category) {
case "Car":
markerCategory = "car";
break;
case "Truck":
markerCategory = "truck";
break;
case "Van":
markerCategory = "van";
break;
case "Bus":
markerCategory = "bus";
break;
case "Motorcycle":
markerCategory = "motorcycle";
break;
case "Recovery Veh":
markerCategory = "truck";
break;
case "Lorry":
markerCategory = "truck";
break;
case "10 Footer Lorry":
markerCategory = "truck";
break;
case "14 Footer Lorry":
markerCategory = "truck";
break;
}
var pictureLabel = document.createElement("img");
pictureLabel.src = "http://track.asiacom.co.th/track/Dashboard/img/categories/marker/" + markerCategory + ".png";
//marker = new google.maps.Marker({ //Default Google Maps
marker = new MarkerWithLabel({
position: myLatLng,
map: map,
//========================================
raiseOnDrag: true,
labelContent: pictureLabel,
labelAnchor: new google.maps.Point(50, 11),
labelClass: "labels", // the CSS class for the label
labelStyle: { opacity: 1 },
category: category,
engine: engine,
company: company,
vechs: vechs,
//animation: google.maps.Animation.DROP,
//icon: image,
icon: new google.maps.MarkerImage(icon, new google.maps.Size(28, 28), new google.maps.Point(0, 0), new google.maps.Point(14, 14)),
shape: shape,
title: asset.LastPos.Asset,
zIndex: asset.LastPos.PosZ
});
markers.push(marker);
/**
* Function to filter markers by category
*/
$(function () {
$('.SelectCategoryFilter').on('change', function () {
var selected = $(this).find("option:selected").val();
for (i = 0; i < assets.length; i++) {
marker = markers[i];
// If is same category or category not picked
if (marker.category == selected || selected.length === 0) {
marker.setVisible(true);
}
//Categories don't match
else {
marker.setVisible(false);
}
}
});
});
/**
* Function to filter markers by engine
*/
$(function () {
$('.SelectEngineFilter').on('change', function () {
var selected = $(this).find("option:selected").val();
for (i = 0; i < assets.length; i++) {
marker = markers[i];
// If is same engine or engine not picked
if (marker.engine == selected || selected.length === 0) {
marker.setVisible(true);
}
//Engine Status don't match
else {
marker.setVisible(false);
}
}
});
});
/**
* Function to filter markers by company
*/
$(function () {
$('.SelectCompanyFilter').on('change', function () {
var selected = $(this).find("option:selected").val();
for (i = 0; i < assets.length; i++) {
marker = markers[i];
// If is same engine or engine not picked
if (marker.company == selected || selected.length === 0) {
marker.setVisible(true);
}
//Engine Status don't match
else {
marker.setVisible(false);
}
}
});
});
/**
* Function to filter markers by Vehicles
*/
$(function () {
$('.SelectVechsFilter').on('change', function () {
var selected = $(this).find("option:selected").val();
for (i = 0; i < assets.length; i++) {
marker = markers[i];
// If is same engine or engine not picked
if (marker.vechs == selected || selected.length === 0) {
marker.setVisible(true);
}
//Engine Status don't match
else {
marker.setVisible(false);
}
}
});
});
//InfoBox Content
var assetTag = asset.Tag;
var assetAddress = asset.LastPos.Location;
var assetSpeed = asset.LastPos.Speed;
var assetMileage = asset.LastPos.Mileage;
var assetFix = asset.LastPos.Fix;
var assetTimestamp = asset.LastPos.Timestamp;
var assetLat = asset.LastPos.PosY;
var assetLong = asset.LastPos.PosX;
var assetBattery = asset.LastPos.Battery;
//Date InfoBox
//Convert Timezone
var Bangkok = moment.tz(assetTimestamp, "Asia/Bangkok");
//Format UTC
var timestamp = moment(Bangkok.format()).format("D-MMM-YYYY, hh:mm:ss A");
// Format for Asset Status Infobox Color
// =================================================================
var assetColor;
if (asset.LastPos.Engine == 'MOVE')
assetColor = "success";
if (asset.LastPos.Engine == 'IDLE')
assetColor = "warning";
if (asset.LastPos.Engine == 'STOP')
assetColor = "danger";
// InfoBox
var assetContent = "<div id='infobox'><h4 id='firstHeading' class='firstHeading'>" + vechs + "</h4>" + "<p class='text-default text-justify bg-" + assetColor + " pad-all' style='height:auto'>"
+ assetAddress + "</p>" + "<table visibly='vehicle:status' class='table table-bordered table-vcenter'>" + "<tbody>" + "<tr>" + "<td>" + "<span class='text-bold'>Device: " + assetTag + "</span>" + "<br />" + "<span class='text-bold'>Category: " + category + "</span>" + "</td>" + "</tr>" + "<td>" + "<span class='text-bold'>Status: " + engine + "</span>" + "<br />" + "<span class='text-bold'>Speed:&nbsp" + assetSpeed + "</span>" + " </td>" + "</tr>" + "<tr>" + "<td>" + "<span class='text-bold'>Mileage: </span>" + assetMileage + "<br />" + "<span class='text-bold'>" + "Battery: " + assetBattery + "</span>" + "</td>" + "</tr>" + "<tr>" + "<td>" + "<span class='text-bold'>" + assetFix + "</span>" + "<br />" + " <span class='text-normal'>" + timestamp + "</span>" + "</td>" + "</tr>" + "</tbody>" + "</table>" + "</div>";
//Marker Details - Info Window
/*=================================================*/
//Start
var infoboxOptions = {
//content: document.getElementById("infobox"),
content: assetContent,
disableAutoPan: false,
maxWidth: 150,
pixelOffset: new google.maps.Size(-140, 14),
zIndex: null,
boxStyle: {
background: "url('http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/examples/tipbox.gif') no-repeat",
opacity: 1,
width: "280px"
},
closeBoxMargin: "12px 4px 2px 2px",
closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif",
infoBoxClearance: new google.maps.Size(1, 1),
isHidden: false,
enableEventPropagation: false
};
//Define the infobox
assets[i].infobox = new InfoBox(infoboxOptions);
//Open box when page is loaded
assets[i].infobox.close(map, marker);
//Total Vehicles
var $result = $('#total-vehicles');
var rows = document.getElementById('assetStatus').getElementsByTagName("tbody")[0].getElementsByTagName("tr").length;
$result.text(rows)
//Table Vehicle List
$("#assetStatus").find("tbody tr").each(function (index) {
$(this).on(
'click',
function () {
map.panTo(markers[index].getPosition());
}
);
});
// Click Marker
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
assets[i].infobox.open(map, this);
map.panTo(this.position);
//setTimeout(function () { initialize(); }, '30000'); //Refresh
setTimeout(function () { AutoRefresh(); }, '3000'); //Refresh
setTimeout(function () { assets[i].infobox.close(map, marker); }, '60000'); //Auto close infobox
}
})(marker, i));
}
return assets;
}
//End
/*=================================================*/
)
}
For the marker part, once you send a request and receive back desired info, parse it, extract location info and you can use the following documentation to put marker on the map: example. There are many options such as set marker display to invisible and visible again, etc. The documentation in the given example contains useful functions which can help you achieve desired effect.

Windows phone 8.1 HTML5 app , using google map api throws me "permission denied" error

I was trying to get the user current location on a google map api. I saw a code at this link and thought to give it a try. The code I used is below (all in index.html). But when I run it on emulator it throws me "Permission denied" error. I searched but could not find the reason. Does anyone know if this is supported or am I making any mistake .
Girija
<!DOCTYPE html>
<html dir="ltr" lang="en-gb">
<head>
<meta charset="utf-8" />
<title>Geolocation API getCurrentPosition example</title>
<style>
#map {
width: 100%;
height: 800px;
}
</style>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body>
<p>Click on the marker for position information.</p>
<div id="map"></div>
<script>
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
alert("Geolocation is not supported by this browser");
}
function displayPosition(position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var options = {
zoom: 10,
center: pos,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), options);
var marker = new google.maps.Marker({
position: pos,
map: map,
title: "User location"
});
var contentString = "<b>Timestamp:</b> " + parseTimestamp(position.timestamp) + "<br/><b>User location:</b> lat " + position.coords.latitude + ", long " + position.coords.longitude + ", accuracy " + position.coords.accuracy;
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
function parseTimestamp(timestamp) {
var d = new Date(timestamp);
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
var hour = d.getHours();
var mins = d.getMinutes();
var secs = d.getSeconds();
var msec = d.getMilliseconds();
return day + "." + month + "." + year + " " + hour + ":" + mins + ":" + secs + "," + msec;
}
</script>
</body>
</html>

Google Maps V3: Draw German State Polygons?

I need to draw colored polygons over certain German states. What's the best way (or easiest, fastest, any really...) to do this? Do I need to somehow get all the outlines as lat/lon points and draw a polygon based on those? Or is there a better way?
You want to do something like this?
http://www.geocodezip.com/geoxml3_test/v3_FusionTables_query_sidebarF_local.html?country=Germany
It uses publicly available data in FusionTables, the Natural Earth Data set.
encrypted ID:
https://www.google.com/fusiontables/DataSource?docid=19lLpgsKdJRHL2O4fNmJ406ri9JtpIIk8a-AchA
numeric ID:
https://www.google.com/fusiontables/DataSource?dsrcid=420419
You can style them (color them) as you like.
code snippet:
// globals
var map = null;
var infoWindow = null;
var geoXml = null;
var geoXmlDoc = null;
var myLatLng = null;
var myOptions = null;
var mapCenter = null;
var geocodeTheCountry = true;
var gpolygons = [];
// Fusion Table data ID
var FT_TableID = "19lLpgsKdJRHL2O4fNmJ406ri9JtpIIk8a-AchA"; // 420419;
var CountryName = "Germany";
google.load('visualization', '1', {
'packages': ['corechart', 'table', 'geomap']
});
function createSidebar() {
// set the query using the parameters
var FT_Query2 = "SELECT 'name_0', 'name_1', 'kml_4326' FROM " + FT_TableID + " WHERE name_0 = '" + CountryName + "' ORDER by 'name_1'";
var queryText = encodeURIComponent(FT_Query2);
// alert("createSidebar query="+FT_Query2);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(getData);
}
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(createSidebar);
var FTresponse = null;
myLatLng = new google.maps.LatLng(37.422104808, -122.0838851);
// these set the initial center, zoom and maptype for the map
// if it is not specified in the query string
var lat = 37.422104808;
var lng = -122.0838851;
var zoom = 18;
var maptype = google.maps.MapTypeId.ROADMAP;
if (!isNaN(lat) && !isNaN(lng)) {
myLatLng = new google.maps.LatLng(lat, lng);
}
infoWindow = new google.maps.InfoWindow();
//define callback function, this is called when the results are returned
function getData(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
FTresponse = response;
//for more information on the response object, see the documentation
//http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
fusiontabledata = "<table><tr>";
fusiontabledata += "<th>" + response.getDataTable().getColumnLabel(1) + "</th>";
// }
fusiontabledata += "</tr><tr>";
for (i = 0; i < numRows; i++) {
fusiontabledata += "<td><a href='javascript:myFTclick(" + i + ")'>" + response.getDataTable().getValue(i, 1) + "</a></td>";
// }
fusiontabledata += "</tr><tr>";
}
fusiontabledata += "</table>";
//display the results on the page
document.getElementById('sidebar').innerHTML = fusiontabledata;
}
function infoWindowContent(name, description) {
content = '<div class="FT_infowindow"><h3>' + name +
'</h3><div>' + description + '</div></div>';
return content;
}
function myFTclick(row) {
var description = FTresponse.getDataTable().getValue(row, 0);
var name = FTresponse.getDataTable().getValue(row, 1);
if (!gpolygons[row]) {
var kml = FTresponse.getDataTable().getValue(row, 2);
// create a geoXml3 parser for the click handlers
var geoXml = new geoXML3.parser({
map: map,
zoom: false,
infoWindow: infoWindow,
singleInfoWindow: true
});
geoXml.parseKmlString("<Placemark>" + kml + "</Placemark>");
geoXml.docs[0].gpolygons[0].setMap(null);
gpolygons[row] = geoXml.docs[0].gpolygons[0].bounds.getCenter();
}
var position = gpolygons[row];
if (!infoWindow) infoWindow = new google.maps.InfoWindow({});
infoWindow.setOptions({
content: infoWindowContent(name, description),
pixelOffset: new google.maps.Size(0, 2),
position: position
});
infoWindow.open(map);
}
function initialize() {
myOptions = {
zoom: zoom,
center: myLatLng,
mapTypeId: maptype
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var geocoder = new google.maps.Geocoder();
if (geocoder && geocodeTheCountry) {
geocoder.geocode({
'address': CountryName + " Country"
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
map.fitBounds(results[0].geometry.viewport);
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
var FT_Query = "SELECT 'kml_4326' FROM " + FT_TableID + " WHERE 'name_0' = '" + CountryName + "';";
var FT_Options = {
suppressInfoWindows: true,
query: {
from: FT_TableID,
select: 'kml_4326',
where: "'name_0' = '" + CountryName + "';"
},
styles: [{
polygonOptions: {
fillColor: "#FF0000",
fillOpacity: 0.35
}
}]
};
layer = new google.maps.FusionTablesLayer(FT_Options);
layer.setMap(map);
google.maps.event.addListener(layer, "click", function(event) {
infoWindow.close();
infoWindow.setContent(infoWindowContent(event.row.name_1.value, event.row.name_0.value));
infoWindow.setPosition(event.latLng);
infoWindow.open(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas {
width: 300px;
height: 100%
}
.infowindow * {
font-size: 90%;
margin: 0
}
<script src="https://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>
<script src="http://www.google.com/jsapi"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<table style="width:100%; height:100%;">
<tr style="width:100%; height:90%;">
<td style="width:60%; height:100%;">
<div id="map_canvas"></div>
</td>
<td>
<div id="sidebar" style="width:300px;height:400px; overflow:auto"></div>
</td>
</tr>
</table>
Also, you could take a look at the Google GeoChart API, which is not that feature-rich but pretty easy to use. Try the following code in the API playground:
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['Province', 'Popularity'],
['Bremen', 100],
['Niedersachsen', 900],
['Saksen', 700],
['Saarland', 300],
['Bayern', 400]
]);
var options = {
region: 'DE',
displayMode: 'regions',
colorAxis: {colors: ['green', 'blue']},
resolution:'provinces'
};
var geochart = new google.visualization.GeoChart(
document.getElementById('visualization'));
geochart.draw(data, options, {width: 556, height: 347});
}
​