I'm developing a mobile web application with Spring MVC. For geolocation, I get the code from here
I ran the demo from my phone on that site and it's asking for location permission, same thing on jsfiddle demo, and it's working. If I don't have Gps enable I get '"Unable to retrieve your location'.
But on my application, I get instantly the above message, without asking for permission(also, removed all blocked apps from chrome).
On PC, geolocation is working,through my app, but on my phone, not.. What can be the problem?Meaning.. why geolocation is not working on my phone through my app, but it's working for other sites. On my phone, goes directly to error() function.
Maybe I have to make some changes in the configuration files,or I don't know..
LE: Tested on 2 more devices, same output:Unable to retrieve your location ... (GPS enabled)
LE2:I checked the error code. I'm getting permission denied
This is the Fiddle
<p><button onclick="geoFindMe()">Show my location</button></p>
<div id="out"></div>
//Javascript
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);
}
You can check this code,
https://github.com/makubex88/MobileHTML5CodeCamp/blob/master/mobilehtml5.html
function showPosition(position) {
var latlon = position.coords.latitude + "," + position.coords.longitude;
var img_url = "http://maps.googleapis.com/maps/api/staticmap?center="+latlon+"&zoom=14&size=400x300&sensor=false";
document.getElementById("mapholder").innerHTML = "<img src='" + img_url + "'>";
}
Related
This script fetches an address when the user inputs a house number and postcode. It works fine in chrome and firefox but doesn't work in IE.
I have already added:
but still no luck. Any ideas?
<script type="text/javascript">
$('#submit').click(function() {
//Get Postcode
var number = $('#number').val();
var postcode = $('#postcode').val().toUpperCase();;
//Get latitude & longitude
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address=' + number + " " + postcode + '&sensor=false',
function(data) {
//Insert
$('#text').text(number + ', ' + data.results[0].formatted_address );
});
});
</script>
Hi I try to get the geolocation of the user using cordova. The longitude and latitude should be get in php and cookies should be created with these values. But when I start the application on my device a blank white screen become show. How can I get the javascript variables with php right?
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
// onSuccess Geolocation
//
function onSuccess(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
window.location.href = "http://".$_SERVER['HTTP_HOST']."/loc/www/login.php?latitude=" + latitude;
window.location.href = "http://".$_SERVER['HTTP_HOST']."/loc/www/login.php?longitude=" + longitude;
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
<?php
$latitude = $_GET["latitude"];
$longitude = $_GET["longitude"];
$t = time() + 60 * 60 * 24 * 1000;
setcookie("latitude", $latitude, $t);
setcookie("longitude", $longitude, $t);
?>
You have PHP variable combined with javascript, please fix to this:
window.location.href = "http://<?php echo $_SERVER['HTTP_HOST'] ?>/loc/www/login.php?latitude=" + latitude;
You change the location previously and then you try to change again, this will not work:
window.location.href = "http://<?php echo $_SERVER['HTTP_HOST'] ?>/loc/www/login.php?longitude=" + longitude;
Why you don't try to create a API to be consumed by your cordova App, send the location to the webservice when cordova is ready?, you could send both values, latitude and longitude to the server and locally keep those values.
I have an MVC4 Web API application where i have my Api Controller and Code-First EF5 database and some JavaScript functions for the functionality of my app including my Ajax Calls for my Web Api Service.I did the project on MVC because i was having trouble installing Cordova in VS2012, so i have decided to use Eclipse/Android Phonegap platform.Is there a way where i can call my web api service and be able to retrieve my database data designed EF5(MVC4) in my Android Phonegap application without having to start from the beginning the same thing again.I know phonegap is basically Html(JavaScript and Css) but i am having trouble calling my service using the same HTML markup that i used MVC4.I am a beginner please let me know if what i am doing is possible and if not please do show me the light of how i can go about this. T*his is my Html code*
<script type="text/javascript" charset="utf-8" src="phonegap-2.9.0.js"></script>
<script type="text/javascript" charset="utf-8" src="barcodescanner.js"></script>
<script type="text/javascript" language="javascript" src="http://api.afrigis.co.za/loadjsapi/?key=...&version=2.6">
</script>
<script type="text/javascript" language="javascript">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
//initialize watchID Variable
var watchID = null;
// device APIs are available
function onDeviceReady() {
// Throw an error if no update is received every 30 seconds
var options = { timeout: 30000 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
}
//declare a global map object
var agmap = null;
// declare zoom control of map
var zoomCtrl = null;
function initAGMap() {
agmap = new AGMap(document.getElementById("MapPanel"));
//TODO: must retrieve coords by device location not hard corded.
agmap.centreAndScale(new AGCoord(-25.7482681540537, 28.225935184269), 5); // zoom level 5 heres
// making zoom controls for map
var ctrlPos = new AGControlPosition(new AGPoint(10, 10), AGAnchor.TOP_LEFT);
zoomCtrl = new AGZoomControl(1);
agmap.addControl(zoomCtrl, ctrlPos);
}
function removeZoomCtrl()
{
zoomCtrl.remove();
}
//function search() {
// var lat = $('#latitude').val();
// var long = $('#longitude').val();
// $.ajax({
// url: "api/Attractions/?longitude=" + long + "&latitude=" + lat,
// type: "GET",
// success: function (data) {
// if (data == null) {
// $('#attractionName').html("No attractions to search");
// }
// else {
// $('#attractionName').html("You should visit " + data.Name);
// displayMap(data.Location.Geography.WellKnownText, data.Name);
// }
// }
// });
//}
//function GetCoordinate() {
//todo: get details from cordova, currently mocking up results
//return { latitude: -25.5, longitude: 28.5 };
}
function ShowCoordinate(coords) {
agmap.centreAndScale(new AGCoord(coords.latitude, coords.longitude), 5); // zoom level 5 here
var coord = new AGCoord(coords.latitude, coords.longitude);
var oMarker = new AGMarker(coord);
agmap.addOverlay(oMarker);
oMarker.show();
//todo: create a list of places found and display with marker on AfriGIS Map.
}
function ScanProduct()
{
//todo retrieve id from cordova as mockup
//This is mockup barcode
//return "1234";
//sample code using cordova barcodescanner plugin
var scanner = cordova.require("cordova/plugin/BarcodeScanner");
scanner.scan(
function (result) {
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
},
//Callback function if barcodedont exist
function (error) {
alert("Scanning failed: " + error);
});
}
//Function to display Success or error in encoding.
function encode(type, data) {
window.plugins.barcodeScanner.encode(type, data, function(result) {
alert("encode success: " + result);
}, function(error) {
alert("encoding failed: " + error);
});}
function GetProductDetails(barcodeId,coords)
{
//Ajax Call to my web Api service
$.getJSON("api/products/?barcodeId=" + barcodeId + "&latitude=" + coords.latitude + "&longitude=" + coords.longitude)
.done(function (data) {
$('#result').append(data.message)
console.log(data)
var list = $("#result").append('<ul></ul>').find('ul');
$.each(data.results, function (i, item)
{
if (data.results == null) {
$('#result').append(data.message)
}
else {
list.append('<li>ShopName :' + item.retailerName + '</li>');
list.append('<li>Name : ' + item.productName + '</li>');
list.append('<li>Rand :' + item.price + '</li>');
list.append('<li>Distance in Km :' + item.Distance + '</li>');
//Another Solution
//var ul = $("<ul></ul>")
//ul.append("<li> Rand" + data.results.productName + "</li>");
//ul.append("<li> Rand" + data.results.Retailer.Name + "</li>");
//ul.append("<li> Rand" + data.results.price + "</li>");
//ul.append("<li> Rand" + data.results.Distance + "</li>");
//$("#result").append(ul);
}
});
$("#result").append(ul);
});
}
function ShowProductDetails()
{
//todo: display product details
//return productdetails.barcodeId + productdetails.retailerName + ': R' + productdetails.Price + productdetails.Distance;
}
//loading javascript api
$(function () {
initAGMap();
var coord = GetCoordinate();
ShowCoordinate(coord);
var barcodeId = ScanProduct();
var productdetails = GetProductDetails(barcodeId, coord);
ShowProductDetails(productdetails);
});
</script>
It looks like you're on the right track. The obvious error right now is that it's using a relative URL (api/products/?barcodeId=) to call the Web API. Because the HTML is no longer hosted on the same server as the Web API (even though you might be running them both on your local machine still), this won't work anymore. You need to call the service with an absolute URL (for example, http://localhost:8888/api/products/?barcodeId=).
Where is your Web API hosted right now and how are you running the Cordova code? If the Web API is up and running on your local machine and your Cordova app is running on an emulator on the same machine, you should be able to call the service by supplying its full localhost path.
If it still doesn't work, you'll need to somehow debug the code and see what the errors are.
I am able to get the user's IP address in my website. Now i need his country, city, region using his IP i got.. I am trying Google's Geolocation API with the following code,
<div id="yourinfo"></div>
<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAp04yNttlQq-7b4aZI_jL5hQYPm-xtd00hTQOC0OXpAMO40FHAxQMnH50uBbWoKVHwgpklyirDEregg"></script>
<script type="text/javascript">
if(google.loader.ClientLocation)
{
visitor_lat = google.loader.ClientLocation.latitude;
visitor_lon = google.loader.ClientLocation.longitude;
visitor_city = google.loader.ClientLocation.address.city;
visitor_region = google.loader.ClientLocation.address.region;
visitor_country = google.loader.ClientLocation.address.country;
visitor_countrycode = google.loader.ClientLocation.address.country_code;
document.getElementById('yourinfo').innerHTML = '<p>Lat/Lon: ' + visitor_lat + ' / ' + visitor_lon + '</p><p>Location: ' + visitor_city + ', ' + visitor_region + ', ' + visitor_country + ' (' + visitor_countrycode + ')</p>';
}
else
{
document.getElementById('yourinfo').innerHTML = '<p>Whoops!</p>';
}
</script>
Really this code is not working for me. It is executing the else part and displays Whoops!.
How to get the Geolocation of users. Any other idea let me know.
I already tried the following code which works well, but takes 6 Seconds of delay in free version. Later i came to know that google is giving this sevice for free.. So i am try on that.
http://services.ipaddresslabs.com/iplocation/locateip?key=SAK58RWP983694534K4Z&ip=".$ClientIP
Thank you in Advance
If you are happy to go with HTML5 you should visit this tutorial on geolocation.
use this on client side:
http://services.ipaddresslabs.com/iplocation/locateip?key=SAK58RWP983694534K4Z&ip=local-ip
its working fine with me.
By the way, the above key is blocked, you have to get new key instead.
i have found a script for geolocation resolve with google
in this code there is a key that is 86 char long
i have opened a google api key for the gmail of the website
it is a short key (only 39 chars)
i then changed the key and run the code.
i get the resolve country location that i need.
i then tried from another ip location (at home) and one with a proxy sever and didn't get any thing
i'm not sure if the api key i'm using is set for public or not- how do i check that?
do i have to pay for using it or can be used only with the free 25,000 request per day?
the code i have tried is:
<script type="text/javascript" src="http://www.google.com/jsapi?key="></script>
<script type="text/javascript">
function geoTest() {
if (google.loader.ClientLocation) {
var latitude = google.loader.ClientLocation.latitude;
var longitude = google.loader.ClientLocation.longitude;
var city = google.loader.ClientLocation.address.city;
var country = google.loader.ClientLocation.address.country;
var country_code = google.loader.ClientLocation.address.country_code;
var region = google.loader.ClientLocation.address.region;
var text = 'Your Location<br /><br />Latitude: ' + latitude + '<br />Longitude: ' + longitude + '<br />City: ' + city + '<br />Country: ' + country + '<br />Country Code: ' + country_code + '<br />Region: ' + region;
} else {
var text = 'Google was not able to detect your location';
}
document.write(text);
}
geoTest();
</script>
Seems like the geolocation is not reliable
See Philippe's answer here Is google.loader.clientlocation still supported