does HTML5 Geolocation work? - geolocation

I have the following script for HTML5 geolocation:
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
body {
padding: 20px;
background-color:#ffffc9
}
p { margin : 0; }
</style>
<script>
function geoFindMe() {
var output = document.getElementById("out");
if (!navigator.geolocation){
output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
return;
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
output.appendChild(img);
}
function error() {
output.innerHTML = "Unable to retrieve your location";
}
output.innerHTML = "<p>Locating…</p>";
navigator.geolocation.getCurrentPosition(success, error);
}
</script>
</head>
<body>
<!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation -->
<p><button onclick="geoFindMe()">Show my location</button></p>
<div id="out"></div>
</body>
</html>
It always gives me the following result:
Your Latitude : 51.5412621
Your Longitude : -0.08813879999999999
Regardless of whether it is on a laptop or mobile and different browsers -- anyone any ideas? it seems unreliable to me!

Related

How to display map using geocode

My Script is
<script type="text/javascript">
var lat = <%= #town.latitude %>,
lon = <%= #town.longitude %>,
map;
function initialize() {
var myOptions = {
center: new google.maps.LatLng(lat, lon)
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
<script type="text/javascript" src="//maps.google.com/maps?file=api& v=2.x&key="My api key"&libraries=places"></script>
I can fetch latitude and longitude but my map is not loading.Could anyone help me with this?
Here is working sample you can update it to your needs (remove what you dont need and add rails variables in place of static lat long):
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: <%= #lat %>, lng: <%= #long %>},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=yourkey&callback=initMap"
async defer></script>
</body>
</html>
This is my sample Home controller index action code:
class HomeController < ApplicationController
def index
#lat = "43.8563"
#long = "18.4131"
end
end

Extract zip folder in iOS using phone gap 2.9.0

I have used zipUtil plugin to extract the zip folder and Below is the image showing how i used ZipUtil plugin in my application. I am using phone gap 2.9.0 and Xcode 5.1, I am very new in phone gap development and I want to unzip/extract the downloaded zip file from the server.
I am able to download the zip file from server and I am getting path of that file as well, But I am not able to extract that zip file.
<!DOCTYPE HTML>
<html>
<head>
<meta name = "viewport" content = "user-scalable=no,width=device-width" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Test Page</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="ZipUtil.js"></script>
<style type="text/css">
* {
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
</style>
<script type="text/javascript" charset="utf-8">
var localPath;
function init() {
document.addEventListener("deviceready", ready, true);
}
function ready() {
console.log("App is ready.");
}
function download() {
// var remoteFile = "https://dl.dropbox.com/u/6731723/a.zip";
var remoteFile = "https://github.com/shazron/ZipUtil/archive/master.zip";
var localFileName = remoteFile.substring(remoteFile.lastIndexOf('/') + 1);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
fileSystem.root.getFile(localFileName, { create: true, exclusive: false }, function (fileEntry) {
localPath = fileEntry.fullPath;
console.log("localPath1:" + localPath);
if (device.platform === "Android" && localPath.indexOf("file://") === 0) {
localPath = localPath.substring(7);
}
console.log("localPath2 save:" + localPath);
var ft = new FileTransfer();
ft.download(remoteFile,
localPath, function (entry) {
console.log("file path:" + entry.fullPath);
var linkopen = document.getElementById("openlink");
linkopen.style.display = "block";
linkopen.href = entry.fullPath;
// var dwnldImg = document.getElementById("dwnldImg");
//dwnldImg.src = entry.fullPath;
//dwnldImg.style.visibility = "visible";
//dwnldImg.style.display = "block";
}, fail);
}, fail);
}, fail);
}
function fail(error) {
console.log("error:" + error.code);
}
function unzip(){
//alert("hi");
// this is both a zip progress and and result handler
var win = function(json) {
if (json.zipProgress) {
// {"zipProgress":{"entryNumber":1,"source":"/path/to/test.zip","filename":"myfolder/myfile.png","entryTotal":10,"zip":false}}
console.log((json.zipProgress.zip? "zip" : "unzip") + " entry " + json.zipProgress.entryNumber + "/" + json.zipProgress.entryTotal + " ("+ ((json.zipProgress.entryNumber/json.zipProgress.entryTotal)*100).toFixed(2) + "%)" );
} else if (json.zipResult) {
// zip ok, and done
// {"zipResult":{"zip":false,"source":"/path/to/test.zip","target":"/path/to/targetfolder/"}}
console.log((json.zipResult.zip? "zip" : "unzip") + " OK: " + JSON.stringify(json));
}
}
// handles failure
var fail = function(obj) {
if (obj && obj.zipResult) {
// zip failed, and done
// {"zipResult":{"zip":false,"source":"/path/to/test.zip","target":"/path/to/targetfolder/"}}
console.log((obj.zipResult.zip? "zip" : "unzip") + " FAIL: " + JSON.stringify(obj));
} else {
// general failure message
console.log("FAIL: " + obj);
}
}
var zu = cordova.require("cordova/plugin/ziputil");
zu.unzip(win, fail, localPath, localPath+'/unzip/');
}
</script>
</head>
<body onload="init();">
Download file
<br />
<br />
<br />
open
</body>
</html>
In the above code I used ZipUtil plugin but its showing error,
2013-12-05 15:10:38.739 TestUnzip[6934:a0b] CDVPlugin class ZipUtil (pluginName: ZipUtil) does not exist.
2013-12-05 15:10:38.740 TestUnzip[6934:a0b] ERROR: Plugin 'ZipUtil' not found, or is not a CDVPlugin. Check your plugin mapping in config.xml.

Fusion infowindow output adding "\n" and geolocation

I've been working on this for a couple so getting to this point should make me very happy. However, I cannot figure out my infowindow output is adding "\n" to every new line. No idea how it's getting there. The geolocation is also being appended to the search result infowindow. I'd like to remove that as well.
Here is a link to the map: http://58design.com/gmaps/
Here is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Sheriff | Zone Leader Look Up</title>
<meta name="author" content="Santa Clarita Valley Sheriff" />
<meta name="copyright" content="Copyright 2013 SCV Sheriff" />
<meta name="keywords" content="Santa Clarita Valley Sheriff, SCV Sheriff, Canyon Country, Valencia, Saugus, Newhall, Castaic, Gorman, Stevenson Ranch, " />
<meta name="description" content="Santa Clarita Valley Sheriff Zone Leader Contact Inforamtion Look Up." />
<meta name="robots" content="index,follow" />
<meta name="Googlebot" content="follow" />
<meta name="googlebot" content="archive" />
<meta name="distribution" content="global" />
<!--Load the AJAX API-->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
google.load('visualization', '1', {'packages':['corechart', 'table', 'geomap']});
//var FusionTableID = 1931355;
var FusionTableID = '1uSGM1yPMJBlu74Znm4fPqdCsJjteB_kQ_nGz3tk';
var map = null;
var geocoder = null;
var infowindow = null;
var marker = null;
function initialize() {
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow({size: new google.maps.Size(150,50) });
// create the map
var myOptions = {
zoom: 10,
center: new google.maps.LatLng(34.452789398370045, -118.51948001245114),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
//layer = new google.maps.FusionTablesLayer(FusionTableID,{suppressInfoWindows:true});
layer = new google.maps.FusionTablesLayer({
map: map,
suppressInfoWindows: true,
heatmap: { enabled: false },
query: {
select: "col2",
from: "1uSGM1yPMJBlu74Znm4fPqdCsJjteB_kQ_nGz3tk",
where: "",
},
options: {
styleId: 2,
templateId: 2
}
});
layer.setMap(map);
google.maps.event.addListener(layer, "click", function(e) {
var content = e.row['description'].value+"<br><br>";
infowindow.setContent(content);
infowindow.setPosition(e.latLng);
infowindow.open(map);
});
}
function showAddress(address) {
var contentString = address+"<br>Outside Area";
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var point = results[0].geometry.location;
contentString += "<br>"+point;
map.setCenter(point);
if (marker && marker.setMap) marker.setMap(null);
marker = new google.maps.Marker({
map: map,
position: point
});
// query FT for data
var queryText ="SELECT 'description', 'Zone Area' FROM "+FusionTableID+" WHERE ST_INTERSECTS(\'Zone Area\', CIRCLE(LATLNG(" + point.toUrlValue(6) + "),0.5));";
// document.getElementById('FTQuery').innerHTML = queryText;
queryText = encodeURIComponent(queryText);
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(openInfoWindowOnMarker);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function openInfoWindowOnMarker(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();
var content = "<b>Outside area</b><br><br>";
var unionBounds = null;
// alert(numRows);
for (var i=0; i < numRows; i++) {
var name = FTresponse.getDataTable().getValue(i,0);
var kml = FTresponse.getDataTable().getValue(i,1);
content = response.getDataTable().getValue(i,0)+"<br><br>";
}
infowindow.setContent(content+marker.getPosition().toUrlValue(6));
// zoom to the bounds
// map.fitBounds(unionBounds);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
google.maps.event.trigger(marker, 'click');
}
</script>
</head>
<body onload="initialize()">
<div id="content">
<h1>SCV Sheriff Reporting Zones</h1>
<p>Use the map below to determine your area's Zone Leader. Enter your street address, city and zip code in the search field below to view the Zone Leader's contact info.</p>
<form action="#" onsubmit="showAddress(this.address.value); return false" style="padding:10px 0px 30px 0px; background:none;">
<label>Address Search</label>
<input type="text" size="60" name="address" value="23920 Valencia Blvd. Santa Clarita, CA 91355" class="address" />
<input type="submit" value="Search" />
</p>
<div id="map_canvas" style="width: 516px; height: 387px; margin-bottom:30px; border:1px solid #999;"></div>
</form>
</div>
<div id="sidebar">
</div>
<div class="clear"><!--clear--></div>
</div>
</body>
</html>
The problem is in the data in your FusionTable (the line feeds are getting translated into "\n"). I fixed the entry for "Gorman" in my example (by removing the extraneous line feeds).
This line of my code is appending the geolocation to the search result infowindow:
infowindow.setContent(content+marker.getPosition().toUrlValue(6));

403 Forbidden when trying to access a merged Fusion Table

I'm getting a 403 Forbidden error when trying to access a merged Fusion Table with the code below. Nor I understand why neither how to resolve this.
Accessing the table that has been merged with another table works like a charme.
The merged table as well as the base tables are publicly downloadable.
Anyone knows what could be wrong?? Is accessing merged tables somehow restricted?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<title>FÖJ-Einsatzstellen</title>
<style>
body {
font-family: Arial, sans-serif;
font-size: 12px;
}
#map-canvas {
height: 500px;
width: 600px;
}
</style>
<script type="text/javascript"
src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script type="text/javascript">
var map;
var infoWindow = new google.maps.InfoWindow();
var DEFAULT_ICON_URL = 'http://g.etfv.co/http://www.google.com'
// EDIT: change this key to your own from the Google APIs Console
// https://code.google.com/apis/console/
var apiKey = 'PLACE_YOUR_OWN_KEY_HERE';
// EDIT: Specify the table with location data and icon URLs
//var tableID = '1i0mw7f4b06sG14-mAO-zEJI1gekZ8wte_J6w05c'; // Basis-Table
var tableID = '1eCPADfnXccPMAYh24W-pUEF-eiKSlOD9e0xSKBM'; // ge-merge-te Table
// Create variables for the columns you need to retrieve from the table
var latitudeColumn = 'Latitude';
var iconUrlColumn = 'Farbcodierung für Marker';
function createMarker (coordinate, url, content) {
var marker = new google.maps.Marker({
map: map,
position: coordinate,
icon: new google.maps.MarkerImage(url)
});
google.maps.event.addListener(marker, 'click', function(event) {
infoWindow.setPosition(coordinate);
infoWindow.setContent(content);
infoWindow.open(map);
});
};
function fetchData() {
// Construct a query to get data from the Fusion Table
var query = 'SELECT '
+ latitudeColumn + ','
+ '\'' + iconUrlColumn + '\''
+ ' FROM '
+ tableID;
var encodedQuery = encodeURIComponent(query);
// Construct the URL
var url = ['https://www.googleapis.com/fusiontables/v1/query'];
url.push('?sql=' + encodedQuery);
url.push('&key=' + apiKey);
url.push('&callback=?');
// Send the JSONP request using jQuery
$.ajax({
url: url.join(''),
dataType: 'jsonp',
success: onDataFetched,
error: onError,
timeout : 7500
});
}
function onError(e) {
alert(e);
}
function onDataFetched(data) {
if(data.error) {
var errs = data.error.errors;
var msg = "";
for (var i in data.error.errors) {
msg +=
parseInt(i, 10)+1 + ". Fehler:" +
"\ndomain: " + errs[i].domain +
"\nmessage: " + errs[i].message +
"\nreason: " + errs[i].reason + "\n";
}
alert(
"Leider sind Fehler aufgetreten (um genau zu sein: " + data.error.errors.length + " Fehler, Code: " + data.error.code + "):\n" + msg
);
return;
}
var rows = data['rows'];
var iconUrl;
var iconUrl_part1 = 'http://chart.apis.google.com/chart?cht=mm&chs=32x32&chco=';
var iconUrl_part2 = '&ext=.png';
var content = "mein content";
var coordinate;
// Copy each row of data from the response into variables.
// Each column is present in the order listed in the query.
// Starting from 0.
// EDIT this if you've changed the columns, above.
for (var i in rows) {
var geocode = rows[i][0].split(",");
coordinate = new google.maps.LatLng(geocode[0],geocode[1]);
if (rows[i][1] != '') { // ensure not empty
iconUrl = iconUrl_part1 + rows[i][1] + iconUrl_part2;
createMarker(coordinate, iconUrl, content);
} else {
createMarker(coordinate, DEFAULT_ICON_URL, content);
}
}
}
function initialize() {
fetchData(); // begin retrieving data from table, and put it on the map
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(48.537778, 9.041111),
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>

Open Fusion Table Layer info window onchange

Using generated code from FusionTablesLayer Wizard, I am trying to determine how to open the info window onchange. The code below displays the marker perfectly, but I would like the info window to open when a different selection (state) is selected, rather than clicking on the marker to trigger info window. Thanks.
Followup:
Following geocodezip's remarks below, the following code works well and has given me a great start! Now to use drop down selector rather than sidebar links...
New working code
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Fusion Table Markers and Sidebar</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['table']});
var map;
var markers = [];
var infoWindow = new google.maps.InfoWindow();
function initialize() {
var us = new google.maps.LatLng(38.24676420846342, -94.82073772499997);
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: us,
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//sidebar to contain link to map marker - Sales Region - and Rep name
var sql = encodeURIComponent("SELECT 'State - Sales Region', 'Representative Contact', Lat, Lon FROM 5555555555 ORDER BY 'State - Sales Region'");
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + sql);
query.send(getData);
}
//simple sidebar and info window style
function getData(response) {
var dt = response.getDataTable();
var side_html = '<table style="border-collapse: collapse" border="1" \
cellpadding="5"> \
<thead> \
<tr style="background-color:#e0e0e0"> \
<th>Area</th> \
<th>Name</th> \
</tr> \
</thead> \
<tbody>';
for (var i = 0; i < dt.getNumberOfRows(); i++) {
var lat = dt.getValue(i,2);
var lng = dt.getValue(i,3);
var area = dt.getValue(i,0);
var pop = dt.getValue(i,1);
var pt = new google.maps.LatLng(lat, lng);
var html = "<strong>" + area + "</strong><br />" + pop;
side_html += '<tr> \
<td>' + area + '</td> \
<td>' + pop + '</td> \
</tr>';
createMarker(pt, html);
}
side_html += '</tbody> \
</table>';
document.getElementById("side_bar").innerHTML = side_html;
}
//use simple default marker
function createMarker(point,info) {
var marker = new google.maps.Marker({
position: point,
map: map
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infoWindow.close();
infoWindow.setContent(info);
infoWindow.open(map,marker);
});
}
function myclick(num) {
google.maps.event.trigger(markers[num], "click");
map.setCenter(markers[num].getPosition());
// map.setZoom(map.getZoom()+2);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width: 900px; height: 600px; position: absolute; left: 10px"></div>
<div id="side_bar" style="width: 200px; height: 600px; position: absolute; left: 920px; overflow: auto;"></div>
</body>
</html>
The only way to open an InfoWindow on a FusionTablesLayer by default is to click on it. To open it from an external event, one option is to create your own InfoWindow. retrieving the content by querying the FusionTable and opening on whatever external stimulus you want.
Example/proof of concept with a sidebar
Example from the documentation

Resources