Js file for find location / Address? - javascript

I need address in project. I am getting address by using Latitude and longitude with including below scripting code.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>
Is there any respective .js file is there to find location instead of loading above URL ?
Please give some suggestions because with out internet connection my app is not loading, It is throwing Application Error.

Click here for your query. I think it will be usefull for you.

why dont you use a function() to get the location and dispaly it within the div??
chk out below:
function Location() {
var latlng = userLatValue + ',' + userLngValue;
var locationUrl = "https://maps.googleapis.com/maps/api/geocode/json?latlng="
+ latlng + "&sensor=false";
var locationRequest = $.ajax({
type : 'GET',
url : locationUrl,
async : false,
data : "json"
});
locationRequest.done(function(data) {
if(data.results.length > 0) {
userLocationName = data.results[0].formatted_address;
//alert('address: ' + userLocationName);
}
});
locationRequest.fail(function(jqXHR, textstatus, error) {
//alert("error:");});
}

Related

Wunderground Geolocation using $.ajax not appending to HTML

I am experimenting using in using $.ajax to use geolocation to input weather data into a page from Wunderground. I am able to successfully input weather data into my page when I manually enter my location into code using plain vanilla JS but want to take it a step further. I am running the following code and get an alert box asking for location but after clicking okay see no code updates to my HTML. When opening the console in dev tools I do not see any error messages.
var Geo={};
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successGeo,error);
}
else {
alert('Geolocation is not supported');
}
function error() {
alert("Cant find you");
}
function successGeo(position) {
Geo.lat = position.coords.latitude;
Geo.lng = position.coords.longitude;
}
function showPosition(position) {
var geoLat = position.coords.latitude;
var geoLong = position.coords.longitude;
var key = "8704dded63fc077d";
var ForecastURL = "http://api.wunderground.com/api/"; + key + "/forecast/q/" + geoLat + "," + geoLong + ".json";
var WeatherURL = "http://api.wunderground.com/api/"; + key + "/conditions/q/" + geoLat + "," + geoLong + ".json";
$.ajax({
url : WeatherURL,
dataType : "jsonp",
success : function(parsed_json) {
var temp_f = parsed_json['current_observation']['temp_f'];
document.getElementById("currentTemp").innerHTML = temp_f;
}
});
$.ajax({
url : ForecastURL,
dataType : "jsonp",
success : function(parsed_json) {
var fore_high = parsed_json['forecast']['simpleforecast']['forecastday'][0]['high']['fahrenheit'];
var fore_low = parsed_json['forecast']['simpleforecast']['forecastday'][0]['low']['fahrenheit'];
document.getElementById("high1").innerHTML = fore_high;
document.getElementById("low1").innerHTML = fore_low;
}
});
} //ends showposition function
I have some div elements set up in the footer of index.html just so I can confirm the elements are being updated. I'll worry more about style and alignment later.
<footer> <!--//contains ajax weather data-->
<div id="high1"></div>
<div id="current_temp"></div>
<div id="low1"></div>
</footer>
I'm pretty stumped as to why I can't get a response, especially since I'm not picking up any errors in the console.

Retrieve XML Data to use webpage

What I am trying to do:
Get location based off of IP (Done)
Use the City and Country code to use openweather's API (Done)
Read the XML into my webpage so that I can display the "Temperature" field.
This is my first venture into using XML in webpages, and I've tried for 3 days now with no success. I have searched google and stackoverflow, and have tried many things so far, including SimpleXMLElement, with no luck.
What I currently have on my page is just a generated link to the XML sheet for your location.
<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
<script language="JavaScript">
var country = geoip_country_code();
var city = geoip_city();
document.write('Link text');
</script>
How am I able to display the text from the required field on my page?
Thanks in advance! :)
It might be easier to change the API call to return JSON, in which case you could then use this code, the temps are stored in temp, temp_min and temp_max.
var country = geoip_country_code();
var city = geoip_city();
$.getJSON('http://api.openweathermap.org/data/2.5/weather?q=' + city + ',' + country + '&mode=json&units=metric', function( json ) {
var temp = json.main.temp;
var temp_min = json.main.temp_min;
var temp_max = json.main.temp_max;
document.write( 'Temp: ' + temp + '<br>');
document.write( 'Temp Min: ' + temp_min + '<br>');
document.write( 'Temp Max: ' + temp_max + '<br>');
});
You could use javascript library to convert the xml into a javascript object - one such library is called xml2json, it works as a jQuery plugin: http://www.fyneworks.com/jquery/xml-to-json/
Then you can simply do:
var xmlObject;
$.ajax({
url: url_of_xml,
success: function(data) {
xmlObject = $.xml2json(data);
}
});
Then you just need to place the data on your page. The object in my example is faked, but it gives you the idea:
// put this line in the success callback of your ajax call
// after you create the xmlObject
$('#temp').html(xmlObject.weather.temp);
To display the temperature you get the XML, and read one of the three temperature attributes from the XML returned:
$.get("http://api.openweathermap.org/data/2.5/weather?q=' + city + ',' + country + '&mode=xml&units=metric", function(xml) {
avg = $(xml).find("temperature").attr("value"));
max = $(xml).find("temperature").attr("max"));
min = $(xml).find("temperature").attr("min"));
(using JQuery)

extjs 4.1 download xml file using ajax

i want to download a file using extjs 4.1.
The file name is "wsnDataModel.xml".
I've tryed with all things suggested in other posts:
//function invoked clicking a button
DwDataModel : function(th, h, items) {
//direct method that build in file in the location calculated below with "certurl" (I've verified)
Utility.GetDataModel(function(e, z, x) {
if (z.message) {
//the server method should give an error message
Ext.create('AM.view.notification.toast', {
title : 'Error',
html : z.message,
isError : true
}).show();
} else {
// navigate to get data
var certurl = 'http://' + window.location.host
+ '/AdminConsole3/' + e;
Ext.Ajax.request({
method : 'GET',
url : 'http://' + window.location.host
+ '/AdminConsole3/' + e,
success : function(response, opts) {
//the following navigate and openthe file in the current browser page.
//I don't want to change the current browser page
//window.location.href = certurl;
//the same behaviour with
//document.location = certurl;
//and this don't work at all
window.open(certurl,'download');
},
failure : function(response, opts) {
console
.log('server-side failure with status code '
+ response.status);
console.log('tried to fetch ' + url);
}
}, this, [certurl]);
}
}, th);
}
the "navigation" redirect the application (i don't want to redirect the application) like this:
and I'would like to download the file like this image:
I think it's very simple. How to do that?
thank you
Very simple: this is the success function.
success: function (response, opts) {
var link = document.createElement("a");
//this gives the name "wsnDataModel.xml"
var fileName = certurl.substring(certurl.lastIndexOf('/') + 1);
link.download = fileName;
link.href = certurl;
link.click();
}

Get position coordinates for an ajax request

Currently working on a weather web-app for iOS. I'm trying to get the coordinates of the user and put the latitude and longitude in my Ajax request (on the api Wunderground) .
Here's my code (EDIT):
<script type="text/javascript">
$(document).ready(function() {
navigator.geolocation.getCurrentPosition(getLocation, unknownLocation);
function getLocation(pos)
{
var lat = pos.coords.latitude;
var lon = pos.coords.longitude;
$.ajax({
url : "http://api.wunderground.com/api/ApiId/geolookup/conditions/q/"+ lat +","+ lon +".json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
}
function unknownLocation()
{
alert('Could not find location');
}
});
</script>
As you can see I "simply" have to create 2 vars lat and lon and add them in my request. I tried a lot of variants but I can't get this code working.
Any idea of what I'm doing wrong ?
Thank you very much !
Your variable declarations are in the middle of the .ajax call, and are making the JavaScript structure invalid. Also, I'm not sure why you're using "function($)", normally with jQuery the $ is reserved and shouldn't be used as a function parameter.
<script type="text/javascript">
$(document).ready(function() {
navigator.geolocation.getCurrentPosition(onPositionUpdate);
});
function onPositionUpdate(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
$.ajax({
url : "http://api.wunderground.com/api/ApiId/geolookup/conditions/q/"+lat+","+lon+".json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
}
</script>

Encoding a JSONP <script src = Request

I am attempting to access Google Books in order to an ISBN Code to get details of a book, I have a number of problem, which are:
A) I am trying to assemble a script request e.g. with the ISBN code concatenated into the URL. I have not managed to do this successfully - and I don't know why.
B) I then want to update a div in the DOM with this generated script dynamically, such that it will then execute.
C) I am finding it a bit of a puzzle as to the format of the returned data and the argument name of the function call contained in the Google response.
Has anyone else encountered the same problem and can offer guidance re A thru C above.
I enclose JavaScript code below.
$(document).ready(function() {
$('#viewbook-button').live('click', function() {
isbnCode = this.text;
alert("ISBN is : " + isbnCode + " " + this.text + " as well");
alert("Getting JSONP Google Books data");
isbnCode = "0451526538";
JSONPstr = '<' + 'script ' + 'src="' + 'https://www.googleapis.com/books/v1/volumes?q=ISBN' + isbnCode;
JSONPstr = JSONPstr + '&callback=handleJSONPResponse">' + '</script>';
alert("un-Escaped JSONP string" + JSONPstr);
escJSONPstr = escape( escJSONPstr );
alert("Escaped JSONP string");
//divstr = "";
//divstr = divstr + escape(<script src=");
//divstr = divstr + encodeURIComponent(https://www.googleapis.com/books/v1/volumes?q=ISBN);
//divstr = divstr + escape(isbnCode);
//divstr = divstr + encodeURIComponent(&callback=handleJSONPResponse);
//divstr = divstr + escape("></);
//divstr = divstr + escape(script);
//divstr = divstr + escape(>);
$('#jsonp-call').html(escJSONPstr);
// This will cause the handleJSONPResponse function to execute when the script is dynamically loadedinto div.
// The data wrapped in a function call will be returned from the Google Books server.
// This will cause the handleJSONPResponse function to execute below.
}); // end viewbook-button
}); // end document.ready
function handleJSONPResponse(response) {
var tmp = response;
alert(tmp);
};
</script>
</head>
<body>
<h2>Show Details of Books Ordered by a Customer</h2>
Get Customer Details
<br/><br/>
<div id="tablist">Tables will be Listed Here</div>
<br/><br/>
<div id="Google-call">The JSONP generated src= statement will go here and execute</div>
</body>
</html>
EDIT:
Problem solved - thanks everyone.
You're reinventing the wheel: jQuery has built-in JSONP support, so you don't need to faff about implementing it yourself. Use the $.ajax method:
$.ajax({
url: 'https://www.googleapis.com/books/v1/volumes?q=ISBN' + isbnCode,
dataType: 'jsonp',
success: function(response) {
console.log(response); // log the response object to the console
}
});
That should be all you need to do.

Categories