Get User Location with Javascript - 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.

Related

Input location with Yahoo's weather API using simpleWeather.js?

I'm building a web-page that shows the weather. I would like for it to be able to use geolocation, as well as the option to manually input a location to pull weather information. I've got the geolocation working fine, but am unsure as to how to add an additional input using either a city or zipcode.
Here's my relevant code:
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(function(position) {
loadWeather(position.coords.latitude + ',' + position.coords.longitude);
});
} else {
loadWeather("", "1062617");
}
function loadWeather(location, woeid) {
$.simpleWeather({
location: location,
woeid: woeid,
unit: 'f',
success: function(weather) {
$(".weather-text").html(weatherText[weather.code]);
$(".weather-icon").html('<i class="icon-' + weather.code + '"></i>');
$(".weather-stats").html('<ul><li><strong>'+weather.city+', ' +weather.region+ '</strong></li>');
$(".weather-stats").append('<li>'+ weather.temp + '°F / '+ weather.alt.temp +'°C</li></ul>');
},
error: function(error) {
$("#weather").html('<p>' + error + '</p>');
}
});
}
I'm pretty new to javascript & jquery, so I understand how to make an input box with HTML but am unsure how to use the user input data to then retrieve the associated weather data.
The getCurrentPosition gives you access to the position interface which then gives you the coordinates. So your if statement results in a latitude and longitude based on the device's Geolocation. In order to get this same information from a user's input (latitude and longitude), you need to convert the input (could be City, State or a full address) to coordinates. I recommend using Google maps API to convert that user input.
Once converted, you can then pass the lat and long to loadWeather(). Here's an example of a user's input (Address) converted:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
var address = jQuery('#address').val();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
jQuery('#coordinates').val(latitude+', '+longitude);
loadWeather(latitude + ',' + longitude);
}
});
</script>
<input id="address" type="text" placeholder="Enter City, State"/>
Of course you would use the above within proper context such as checking whether geolocation worked first or whenever a user actually enters their address. You might need a Google Maps API for this bit that should be easy to get.
Give it a shot, if stuck, check out this fiddle: jsfiddle
EDIT:
I grabbed Yahoo's Weather API endpoint and here is working fiddle:
https://jsfiddle.net/mjsgwq55/3/
I highly recommend logging variables so you can tell what time of data they contain. In your fiddle, you tried to access a property that doesn't exist in the object. Logging that would easily show you what to use.

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

How to use asynchronous Javascript?

I am using Google maps to get address in mobile application. Code is working fine when there is an internet connection. If not then my app takes 1 minute to load or sometimes it shows an application error. This is due to loading a URL within the script, so I wanted to load my script asynchronously. Can anyone give me some logic to solve my issue, how do I rewrite the below script asynchronously?
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true">
function address()
{
var geocoder ;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);
geocoder.geocode({'latLng': latlng}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
if (results[0])
{
var add= results[0].formatted_address ;
document.getElementById("location").innerHTML="Location : " + add ;
}
else
{
document.getElementById("location").innerHTML="No Results found " ;
}
}
else
{
//document.getElementById("location").innerHTML="Geocoder failed due to: " + status;
//alert("Geocoder failed due to: " + status);
}
});
}
This should do it:
jQuery.getScript('https://maps.googleapis.com/maps/api/js?sensor=true', address);
BTW, getScript() is a helper function for jQuery.ajax(). if you use the latter you can take more control and set more options, specifically a timeout parameter so it does not just spin for ever or the cache parameter so that you don't have to look it up all the time
A fiddle that's similar. Sorry fiddles can't use external resources directly so I have to create a simpler script request but you can see the callback is referencing the new javascript.

Google Maps Geocoder not giving results

I am using jQuery with the Google Maps API V3's Geocoder. The site user enters a location in the textbox and clicks on the submit button, which calls the code below to geocode the address given by the user into LatLng coordinates.
$(function(){
$("#searchbox_form #search_button").click(function(){
var address = $("#location").val();
var geocoder = new google.maps.Geocoder();
alert(address);
geocoder.geocode( { 'address': address}, function(results, status) {
alert("123");
if (status == google.maps.GeocoderStatus.OK) {
$("#user_lat").val(results[0].geometry.location.lat);
$("#user_lng").val(results[0].geometry.location.lng);
alert("lat: " + $("#user_lat").val());
alert("lng: " + $("#user_lat").val());
} else {
alert("asdasdasd");
alert(status);
}
});
});
});
However there is some problem. You will notice I placed several alert()s in the code. When 'Boston' is entered into the textbox and the submit button is clicked, only alert("address"); is executed showing Boston but alert("123") does not run. Did something go wrong somewhere?
Solution is to disable the submitting of the form :)
Check in any web - debugger whether any request is even made or not?
The code seems fine to me.

Getting an GET-error when nestling JQuery/json-calls: Update

So what i'm trying to do is, by using to services for ip-lookup and geo-lookup, placing a marker on a map at the visitors location.. for now.
This is later to be used as a script, to be placed on pages, to feed a database with user locations from where they are visiting our sites.
Then by reading from the db, liveplacing dots on a map where users are located. A sort of dashboard.
Anyhow..
//
[ Above this i've declared a googlemap, hence the google.maps-references ]
$('#addButton').click(function(){
var ipurl = 'http://jsonip.appspot.com/';
//displays the users ip-adress in json-format
$.getJSON(ipurl,function(json){
var ip = json.ip;
//gets the ip from the above url
var geourl='http://freegeoip.appspot.com/json/' + ip;
//gets location details from the ip in json-format
$.getJSON(geourl,function(json){
var myLatlng = new google.maps.LatLng(json.latitude, json.longitude);
//set the position for the map
var marker = new google.maps.Marker({
position: myLatlng,
title:"Hello World!"
});
marker.setMap(map);
});
});
});
When I'm trying to run this, I think I've come to the conclusion that I'm getting a GET-error or something when the script tries to run the second JSON-function. It simply skips it.
Any idea what could cause this?
EDIT:
I've changed the variable for the second JSON-request. And it works. But just when i try it out while it's on my local machine. With Safari.
Tried it in Chrome and Firefox. Both local and on a server. Just wont work.
Red marked text in FireBug:
GET http://example.com/json/ 200 OK 168ms
$(document).ready(function(){
$('#addButton').click(function(){
var ipurl = 'http://jsonip.appspot.com/';
$.getJSON(ipurl,function(json){
var ip = json.ip;
var url='http://freegeoip.appspot.com/json/' + ip;
$('#result').append(
'<p>1: ' + ip + '</p>' +
'<p>2: ' + url + '</p>');
$.getJSON(url,function(json2){
$('#result').append('<p>' + json2.longitude + ' / ' + json2.latitude + '</p>');
});
});
});
});
Try changing the json parameter of the second function. I think you get into trouble when using the same parameter name for both functions.

Categories

Resources