Ways to get location of the client from the browser? - geolocation

What i need is the lat/long of the client(via browser)
Found some articles on the net,found some in stack overflow itself(an old article) Get GPS location from the web browser. it was answered almost 18months ago -- wondering if there's any other(more efficient) way of getting the information of the location of the user from the browser.
Soo far,found 2
using Maxmind
http://coding.smashingmagazine.com/2010/03/08/entering-the-wonderful-world-of-geo-location/
Other,using google's api
http://briancray.com/2009/05/29/find-web-visitors-location-javascript-google-api/
w3c's geo api will have downward compatibility issues: http://dev.w3.org/geo/api/spec-source.html ,so not choosing that.
Found a site, www.drumaroo.com -- requests for the location to be shared the 1st time when we drop into the site.Needed something similar

The user can be located by using following ways:-
Using the IP addr.
easiest to achieve but most unreliable due to the uncertainty of network addresses /
topologies.
Using the latitude, longitude pair
most accurate solution, but most of the end users don’t know about their latitude,
longitude value.
Using the zipcodes
nice to think but quite difficult to achieve, although ZipCodes are being used for
quite a long time but this is not a standard yet. (see link
http://en.wikipedia.org/wiki/Postal_code ). ZipCode alone is not sufficient for
calculation of distance we need to convert it to latitude, longitude pair which is an
overhead.
Using user’s address
most compelling thought since each user will have at least one geographic address.
Address alone is not sufficient for calculation of distance we need to convert it to
latitude, longitude pair which is an overhead.
The Best option will be to use options 2,3.4 together, You can do that in two steps:-
First determine the latitude, longitude from the address.
Then use this lat, long value for further processing i.e. storing in
database etc.
For various options available for this see the answer of this question

Try HTML5 geolocation
function init() {
var mapOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
}
} else {
alert('Geolocation not detected');
}
}

Here is geolocation described:
http://www.w3schools.com/htmL/html5_geolocation.asp
The lat/lng can then be reverse-geocoded to find the country, address. etc.
https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse

https://developers.google.com/maps/documentation/javascript/examples/map-geolocation . simply click on javascript+html and copy the code into an html file.

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Reverse Geocoding</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
if (navigator.geolocation) {
var location_timeout = setTimeout("geolocFail()", 10000);
navigator.geolocation.getCurrentPosition(function(position) {
clearTimeout(location_timeout);
var lat = position.coords.latitude;
var lng = position.coords.longitude;
geocodeLatLng(lat, lng);
}, function(error) {
alert("inside error ");
clearTimeout(location_timeout);
geolocFail();
});
} else {
alert("Turn on the location service to make the deposit");
// Fallback for no geolocation
geolocFail();
}
function geolocFail(){
alert("Turn on the location service to make the deposit");
document.write("Turn on the location service to make the deposit");
}
/*if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
alert("Geocoder failed");
} */
function initialize() {
geocoder = new google.maps.Geocoder();
}
function geocodeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
//formatted address
var add= results[0].formatted_address
alert(add);
//city data
//alert(city.short_name + " " + city.long_name)
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
</body>
</html>

This is HTML code to trace the device(Browser/Mobile) location .Just save the above file as .html extension and browse it from any browser on your system or Mobile ,it will display the user current location.

Related

Codepen not recognizing navigator

I'm trying to get the longitude and latitude of the user but I'm seeing that in Codepen the navigator.geolocation.getCurrentPosition is not working.
$(document).ready(function() {
if(navigator.geolocation){
function success(position){
var lat = position.coords.latitude;
var long = position.coords.longitude;
$("p").html("latitude: " + lat + "<br>longitude: " + long);
};
function failure(){
$("p").html("Not working");
};
navigator.geolocation.getCurrentPosition(success,failure);
};
});
Output:
Not Working
So, is there a way around it or do I have to use another API for this?
This is a repeat of javascript - geolocation not working in codepen.
Chrome excerpt:
getCurrentPosition() and watchPosition() are deprecated on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS.

Visualize Neo4j-Spatial database in a map

I've been able to import some shapefiles to Neo4j 2.3.1.
Now how do I view this data on a map?
I have tried the Wiki instructions on GeoServer and uDig, but both of them are outdated and I couldn't get it to work.
Is there any recent tutorial or other tool that can solve this problem?
I've used neo4j-spatial with Mapbox.js for visualizing geometries in a map.
For my use case I indexed US Congressional district geometries in neo4j-spatial then query the spatial index based on where a user clicks on the map, returning the closest district including the WKT string and the results of a Cypher query. To render the WKT polygon in the map I wrote a simple javascript function to parse that into an array of points to add a map annotation.
Here are some relevant code snippets:
Create the map and define a click handler for the map:
L.mapbox.accessToken = MB_API_TOKEN;
var map = L.mapbox.map('map', 'mapbox.streets')
.setView([39.8282, -98.5795], 5);
map.on('click', function(e) {
clearMap(map);
getClosestDistrict(e);
});
Handle mouse click
/**
* Find the District for a given latlng.
* Find the representative, commitees and subjects for that rep.
*/
function infoDistrictWithinDistance(latlng, distance) {
var districtParams = {
"layer": "geom",
"pointX": latlng.lng,
"pointY": latlng.lat,
"distanceInKm": distance
};
var districtURL = baseURI + findGeometriesPath;
makePOSTRequest(districtURL, districtParams, function (error, data) {
if (error) {
console.log("Error");
} else {
console.log(data);
var params = {
"state": data[0]["data"]["state"],
"district": data[0]["data"]["district"]
};
var points = parseWKTPolygon(data[0]["data"]["wkt"]);
makeCypherRequest([{"statement": subjectsQuery, "parameters": params}], function (error, data) {
if (error) {
console.log("Error");
} else {
console.log(data);
var districtInfo = data["results"][0]["data"][0]["row"][0];
districtInfo["points"] = points;
districtInfo["state"] = params["state"];
districtInfo["district"] = params["district"];
console.log(districtInfo);
addDistrictToMap(districtInfo, latlng);
}
});
}
});
Parse WKT into an array of points
/**
* Converts Polygon WKT string to an array of [x,y] points
*/
function parseWKTPolygon(wkt) {
var pointArr = [];
var points = wkt.slice(10, -3).split(",");
$.each(points, function(i,v) {
var point = $.trim(v).split(" ");
var xy = [Number(point[1]), Number(point[0])];
pointArr.push(xy)
});
return pointArr;
}
The code is in this repo. You can see the simple map demo here (just click anywhere in the US to get started). There is also a recent blog post about this example here.

angularjs:ionic IOS emulator is showing wrong GPS co-ordinates

In ionic angularjs
I'm trying to get the Latitude and Longitude of my current location.
It is giving my current location correctly when I'm running it on the browser , but when I run it on IOS emulator it is giving some sanfransisco address.
COntroller.js
ionic.Platform.ready(function() {
LocationService.GetLocation().then(function(data){
console.log(data.latitude,data.longitude);
var code="https://maps.googleapis.com/maps/api/geocode/json?latlng="+data.latitude+","+data.longitude;
$http.get(code).success(function(dataval){
//console.log(dataval.results[0]);
$("#Locationval").text(dataval.results[0]["formatted_address"])
});
});
});
Service.js
appnService.factory('LocationService', function($q){
var currentLocation = {
latitude:"",
longitude:""
}
return {
GetLocation : function(){
var d = $q.defer();
//console.log(d);
navigator.geolocation.getCurrentPosition(function (pos) {
currentLocation.latitude = pos.coords.latitude;
currentLocation.longitude = pos.coords.longitude;
d.resolve(currentLocation);
});
return d.promise
}
};
});
On browser I'm Getting latitude=11.9384867 Longitude=79.8352657(These are correct)
On IOS emulator I'm getting latitude=37.785834 Longitude= -122.406417 (These are wrong)
Please help me with this
Thankyou

automatic geolocation in ruby

I jus started learn ruby on rails and currently I am creating my first rails app. And I ran into some problems. In my app, I would like to get user's position (latitude, longitude). So I can put the button "find me" and return user's locations. But I would like to load my page and show my position (latitude, longitude), don't press any buttons. And then use lat and lng in my controllers. How can I do this?
Add the below script in your view page.You may go ahead and modify this as needed as to show/customise messages and buttons.Remember to have a dedicated div with id="map-canvas" to show you map on the page.
I have used geocomplete.js to show map and allow user to enter places from search box .You may remove the scripts using geocomplete if not needed.
<script type="text/javascript">
// Enable the visual refresh
// google.maps.visualRefresh = true;
var map;
var mapOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: '<p>You are here!</p>'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}//initialize ends
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = '<p>Unable to find the current location</p>';
} else {
var content = '<p Your browser doesn\'t support geolocation.</p>';
}
var options = {
map: map,
zoom: 5,
position: new google.maps.LatLng(60, 105),
content: content
};
var marker = new google.maps.Marker({
position: new google.maps.LatLng(60, 105),
map: map,
animation: google.maps.Animation.DROP,
title: 'Sorry,we were unable to find your location'
});
marker.setAnimation(google.maps.Animation.BOUNCE);
var infowindow = new google.maps.InfoWindow(options);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
infowindow.open(map,marker);
map.setCenter(options.position);
}//handleNoGeolocation ends
//load the page and execute above scripts
$(document).ready(function(){
$('#map-canvas').html("<p class='text-center text-alert'>Loading map...</p>").show(3000);
//load the map after 2 seconds
setTimeout('initialize()', 3000);
// $("#geocomplete").geocomplete({
// map: ".map-canvas-guest"
// });
//you may use this or remove this section using geocomplete.js if not needed.
$("#geocomplete").geocomplete();
$("#geocomplete").geocomplete(mapOptions).bind("geocode:result", function(event, result){
console.log(result.formatted_address);
//use this user entered address and you may call ajax here as well
})
})//document ends
</script>

Google Maps JS API v3 not Geolocating with Phonegap iOS 3.5.0 and jQuery Mobile

The Setup
Currently building my phone gap iOS app which includes geolocation in addition to sending the results to a database and getting back nearby locations. Because I am using jQuery Mobile and Phonegap, I was testing on a browser to perfection, geolocation was success and everything returned was as well. On the iOS device, not so much. When sending a set latitude and longitude, everything returned successfully, but when using the google maps geolocation, and eventually the cordova plugin for geolocation, both failed as unable to find my location, even though they are the exact same code, minus the phone gap initializer on the website.
The Code
jQuery
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
$(document).ready(function () {
//Load Google Map & Geolocate
$(document).on("pagecreate", "#game", function () {
// keep as separate function call to allow for DOM to update after a tag
loadGoogleMap();
});
function loadGoogleMap() {
var defaultLatLng = new google.maps.LatLng(34.0983425, -118.3267434); //default location is Hollywood, CA
if (navigator.geolocation) {
function success(pos) {
//set fields for current user latitude and longitude
$("#lat_in").val(pos.coords.latitude);
$("#lon_in").val(pos.coords.longitude);
//location found
drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
}
function fail(error) {
//try cordova geolocation plugin
function onSuccess(position) {
alert("CDV position success");
//alert(position.coords.latitude);
//alert(position.coords.longitude);
}
function onError(error) {
alert("CDV position error");
//alert("code: " + error.code + "\n" + "message: " + error.message);
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
alert("CDV position fail. Google geolocate fail"); //WHERE THE ERROR IS THROWN. THIS IS ALWAYS THE OUTCOME
//drawMap(defaultLatLng); //Failed to find location. Show default location
}
//Geolocate. Cache location for 5 mins. Timeout after 6 seconds
navigator.geolocation.getCurrentPosition(success, fail, {
maximumAge: 500000,
enableHighAccuracy: true,
timeout: 6000
});
} else {
drawMap(defaultLatLng); //No geolocation support, show default map
}
function drawMap(latlng) {
//Collect Data to Send
var uname = $("#unm_in").val();
var lat = $("#lat_in").val();
var lon = $("#lon_in").val();
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
//update latitude and longitude on DB for logged in user && get nearby users
$.post("PHP_ON_SERVER", {
uname: uname,
lat: lat,
lon: lon
}, function (data) {
$.each(data, function (key, value) {
//Define variables
var allUsrLoc = new google.maps.LatLng(value.lat, value.lon);
var contentString = value.uname;
var mkrImg = "inUsrIcon.png"; //icon for logged in user
var inUserName = value.fname + " " + value.lname;
//if info belongs to current user
if (contentString === uname) {
var marker = new google.maps.Marker({
position: allUsrLoc,
map: map,
title: "Player",
icon: mkrImg
});
//change header to name and points
$("#inUserInfo").text("Hi " + inUserName + " || You have " + value.points + " points");
//disable tag button if not it
if (value.isit === "notit") {
$("#tagBtn").addClass("ui-state-disabled");
}
}
//if not current user and is not it
else if (contentString != uname && value.isit != "it") {
var marker = new google.maps.Marker({
position: allUsrLoc,
map: map,
title: "Player"
});
google.maps.event.addListener(marker, 'click', function () {
//Change selected player hidden field to match marker
$("#unm_sel").val(contentString);
$("#lat_sel").val(value.lat);
$("#lon_sel").val(value.lon);
$("#isit_sel").val(value.isit);
//Change tag button to selected player's username
$("#tagBtn").text("Tag " + contentString);
});
}
//no condition for if not current user and is it. TBD if anything will come
});
}, "json");
} //end drawMap
} // end loadGoogleMap
}
HTML
<div data-role="content" role="main" id="map-canvas">
<!-- Map loads here -->
</div>
Some More to Know
I have been reading up on other related questions, but none of the others do work. Either they say use the plugin, which I am to no avail, or set <access origin="*" /> which I am doing already. In addition, most of the other questions revolve around pre-3.0.0 versions of phone gap, which was its own monster. Also, the map loads, just no markers display. On the DB, the user who's location is being updated is set to (0,0). Lastly, when using geolocation in any other app, the iOS device I test on is successfully finding my location. In addition, I am testing on the same WiFi network as the browser which worked, so anything relating to internally being unable to locate due to network or hardware is ruled out.
If you want to see the working example, just ask.

Resources