400 Bad request with Google reverse geocoding - javascript

Im trying to display my location on my web app, it shows my coordinate correctly, but when i try to employ google geocoding, it keeps showing 400(bad request) in the console.
$("#location-button").click(function() {
// document.getElementById('#location-button').click(function(){
if(navigator.geolocation)
navigator.geolocation.getCurrentPosition(function(position){
console.log(position);
$.get("http://maps.googleapis.com/maps/api/geocode/json?latlng="+ position.coords.latitude + "," + position.coords.longitude + "?key= "+"AIzaSyD3rQONJZostxOofIY9ZfaAsta-fqf1nBbs" + "&sensor=false", function(data) {
// $.get("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "?key= "+"AIzaSyD3rQONJZostxOofIY9ZfAsta-fqf1nBbs" + "&sensor=false", function(data) {
console.log(data);
})
Please note im not good with javascript, i just want to use this bits

Related

Get User Location with Javascript

I want to get the the users current location address(city, street etc) on click event.
I have tried html5 geolocation and tried to console the data. on button click i am checking geo location is supported by creating alert box, and its executes succesfully, But its not printing any values in the console.
HTML
<div id="navbar"><span> Geolocation API</span></div>
<div id="wrapper">
<button id="location-button">Get User Location</button>
<div id="output"></div>
My script
<script>
$('#location-button').click(function(){
if (navigator.geolocation) {
alert("it is supported");
navigator.geolocation.getCurrentPosition(function(position){
console.log(position);
$.get( "http://maps.googleapis.com/maps/api/geocode/json?latlng="+ position.coords.latitude + "," + position.coords.longitude +"&sensor=false", function(data) {
console.log(data);
})
var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + position.coords.latitude + "," + position.coords.longitude + "&zoom=13&size=800x400&sensor=false";
$('#output').html(img);
});
}
else
{
console.log("geo location is not supported")
}
});
</script>
I want to get the full address of the users location.
You may visit this jsfiddle sample that demonstrates your use case.
Kindly note that it is not recommended to use web service in the client side, as web service requests are recommended to be used for server side requests.
As you can see below, what I used is a Geocoder Service instead of the Web Service Geocoding
geocoder.geocode( { 'location': pos}, function(results, status, infowindow) {
if (status == 'OK') {
console.log(results[0].formatted_address);
infoWindow.setContent('Location found: '+ results[0].formatted_address);
infoWindow.setPosition(pos);
infoWindow.open(map);
} else {
console.log('Geocode was not successful for the following reason: ' + status);
}
});
you simply can't! Geolocation use triangulation or GPS from the mobile and you'll get get longitude and latitude values or even the IP and you'll get nearest distributor device(haven't right word in english).
Obviously for geolocation the user have to authorize it too.
So if you want address the simpliest is to ask by a form. You can use a map related with longit/latitude matching but it'll be a pain and waste to do because you've to use all maps and places on earth related to use it that way.

Html geolocation not working on my mobile web application | Spring MVC

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 + "'>";
}

Geolocation always shows Moscow Javascript/JQuery/JSON (Open Weather API)

EDIT: Just finished up the project. New link is up here! http://codepen.io/myleschuahiock/full/pyoZge/
I'm in the process of making a Weather Widget App for my Free Code Camp. Everything except the "city" is a static placeholder. I'm using the Open Weather Api, which makes us to a latitude and longitude. For debugging purposes, I placed the longitude and latitude of my area underneath the time placeholder.
My problem is that when I statically input the lat and lon on my API link, it works just fine. It returns "Mandaluyong City", a nearby city where I live:
http://api.openweathermap.org/data/2.5/weather?lat=14.603814400000001&lon=121.04907589999999&id=524901&APPID=ca8c2c7970a09dc296d9b3cfc4d06940
But when I do this, where I dynamically add mylatitude and mylongitude, to complete the API link:
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + mylatitude + "&lon=" + mylongitude + "&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
I always get "Moscow" as my city.
Please take a closer look at my Javascript/JQuery code here!
http://codepen.io/myleschuahiock/pen/zqYzWm?editors=0010
Thank you very much! Much appreciated!
Easy solution for you.
Move the $.getJSON() into your if condition, why attempt to query the weather if the client blocks the location?
As Jaromanda X has pointed out:
navigator.geolocation.getCurrentPosition is asynchronous. So, you're calling $.getJSON before the location is actually determined.
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
$('.geo').html(position.coords.latitude+ " " +position.coords.longitude);
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat="+position.coords.latitude+"&lon="+position.coords.longitude+"&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
});
});
}else{
$(".geo").html("Please turn on Geolocator on Browser.")
}
});
I hope this helps. Happy coding!
Added
getName(mylatitude, mylongitude);
and changed
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + mylatitude + "&lon=" + mylongitude + "&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
});
to
function getName(mylatitude, mylongitude){
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + mylatitude + "&lon=" + mylongitude + "&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
});
}
http://codepen.io/anon/pen/Yqzvbd?editors=0010
You can use third-party IP API that provides the name of the city. With use jQuery function $.getJSON()
var openWeatherMap = 'http://api.openweathermap.org/data/2.5/weather';
var APPID = 'APPID';
var ipAPI = 'http://ip-api.com/json/';
$.getJSON(ipAPI).done(function(location) {
$('.geo').html(location.lat + " " + location.lon);
$('.city').html(location.city);
$.getJSON(openWeatherMap, {
lat: location.lat,
lon: location.lon,
APPID: APPID
}).done(function(weather) {
$('#temperature').html(weather.main.temp - 273.15);
})
})
OpenWeatherMap provides the temperature in Kelvin on this I did weather.main.temp - 273.15 to get Celsius

Converting an MVC4 Web API Application to Phonegap Android Application

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.

How to get country code information using geonames service api not the html5 location object thing

I am trying to get the country code of the user's current location using Geonames Servcie API. And I believe geonames service API will return me two letter country code instead of three letter country code and I need three letter country code. So for this, I have made the mapping between two letter country code and three letter country code.
Below is my code, and some how, my alert box is not working at all. I am pretty much sure I am missing something?
<html>
<head>
<title>Visitor's location</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready( function() {
$.getJSON('http://ws.geonames.org/countryCode', {
lat: position.coords.latitude,
lng: position.coords.longitude,
type: 'JSON'
}, function(result) {
alert('Country: ' + result.countryName + '\n' + 'Code: ' + result.countryCode);
$('#newURL').attr('href','https://www.google.com&jobid='+result.countryCode);
});
});
</script>
</head>
<body>
<a id="newURL">URL</a>
</body>
</html>
What wrong I am doing in my above code? Below is the error I am getting on the console.
Uncaught ReferenceError: position is not defined
Using HTML5 Geolocation you could do :
$(document).ready( function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
$.getJSON('http://ws.geonames.org/countryCode', {
lat: position.coords.latitude,
lng: position.coords.longitude,
type: 'JSON'
}, function(result) {
alert('Country: ' + result.countryName + '\n' + 'Code: ' + result.countryCode);
$('#newURL').attr('href','https://www.google.com&jobid='+result.countryCode);
});
});
}
});
FIDDLE
Or you could use a service:
$(document).ready( function() {
$.getJSON("http://freegeoip.net/json/", function(result){
alert('Country: ' + result.country_name + '\n' + 'Code: ' + result.country_code);
$('#newURL').attr('href','https://www.google.com&jobid='+result.country_code);
});
});
FIDDLE

Categories

Resources