I have simple idea:
Get geolocation from one API (http://ip-api.com/json) and display it
Base on this geolocation find (using another api http://api.geonames.org/) closest mountains within a radius of 70km
and display it names
I have a problem with third point - I get a link (displaying as alert) which leads me to the list of objects(?) in JSON format but ... I want an alert or html display with full list of mountains name. How to achieve this ?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="api_try.css">
<script src="api_try.js"></script>
</head>
<body>
<button type="submit" class="form-btn" value="sbutton" onsubmit="">Try!</button>
<div id="geo_view">..</div>
<div id="mountains">..</div>
</body>
</html>
JS:
$(document).ready(function () {
$(".form-btn").on("click", function () {
var lat;
var lon;
$.get("http://ip-api.com/json", function (data) {
lat = data.lat;
lon = data.lon;
$('#geo_view').html(data.city);
alert(data.city);
});
var url1 = "http://api.geonames.org/findNearbyJSON?lat=";
var url2 = "&lng=";
var url3 = "&featureCode=MTS&radius=70&username=zebru";
var url = url1 + lat + url2 + lon + url3;
alert(url);
alert("2");
$.get(url,function(data){
alert("3");
var mt = $('#mountains").html(data.toponymName);
alert(mt);
});
});
});
Related
I'm trying to make a webpage with a button. When the button clicked the webpage has to display the user's current location and the user's timezone.
I'm locating users' latitude & longitude by jquery and for the location name I use reverse geocoding of google geocode API and for timezone google timezone API.
Function for the latitude & longitude and function for the reverse geocoding works well. But the function for the timezone isn't working. The unworking function I wrote for this API is the last function in the JS code. I don't understand how to solve this problem.
I need someones' help with this.
HTML Part
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>
<body>
<h1>Hello let's trace your location</h1>
<button onClick="getLocation()">Get Location</button>
<div id="output"></div>
<script language="javascript" type="text/javascript" src="java.js">
</script>
</body>
</html>
JS PART
var x = document.getElementById('output');
function getLocation(){
if (navigator.geolocation){
x.innerHTML = "Supporting";
navigator.geolocation.getCurrentPosition(showPosition);
}
else{
x.innerHTML = "Browser not supporting";
}
}
function showPosition(position){
var locAPI = "https://maps.googleapis.com/maps/api/geocode/json?latlng="+position.coords.latitude.toFixed(6)+","+position.coords.longitude.toFixed(6)+"&key=<key>";
//x.innerHTML += locAPI;
$.get({
url: locAPI,
success: function(data){
console.log(data);
var num = data.results.length - data.results.length;
var add1 = data.results[num].address_components.length - 1;
var add2 = data.results[num].address_components.length - 2;
x.innerHTML = num;
x.innerHTML += add1;
x.innerHTML += add2;
x.innerHTML += data.results[num].address_components[add2].long_name;
x.innerHTML += "<br/>";
x.innerHTML += data.results[num].address_components[add1].long_name;
}
});
}
function showPosition(location){
var timeAPI = "https://maps.googleapis.com/maps/api/timezone/json?location="+location.coords.latitude.toFixed(6)+","+location.coords.longitude.toFixed(6)+"×tamp=<key>";
//x.innerHTML += timeAPI;
$.get({
url:timeAPI,
success:function(data){
console.log(data);
}
});
}
}
I´m new on this and I´m having a hard time tryng to do something I think must be simple.
I have a lot of pages hosted on https://www.something.com/path/NUMBER/path/path
Inside those pages I have a button that links to https://www.example.com/path/REPLACE/path
I would like to change REPLACE on my link with NUMBER on the address bar.
This is my code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
var newURL = window.location.protocol + "://" + window.location.host + "/" + window.location.pathname;
pathArray = window.location.pathname.split( '/' );
var part_2 = pathArray[2];
var mylink = "https://www.example.com/path/" + part_2 + "/path/page.html";
});
</script>
<p>BUTTON</p>
</body>
</html>
Thank you very much for your help!
try this.
Url1:- https://www.something.com/path/NUMBER/path/path;
Url2:- https://www.example.com/path/REPLACE/path;
url2 = url2.split('/').map(a => {
if(a == 'REPLACE')
return 'NUMBER';
else
return a;
}).join('/');
If you want to change using Javascript, you can do as below:
var url = "https://www.something.com/path/NUMBER/path/path";
var oldUrl = "https://www.example.com/path/REPLACE/path/path";
var regex = /https:\/\/www\.something\.com\/path\/(\w*?)\/.*/g;
var match = regex.exec(url);
oldUrl = oldUrl.replace("/REPLACE/", "/"+match[1]+"/");
console.log(oldUrl);
-- EDIT --
Another example to replace using browser URL and replace the second path without considering the remaining URL or paths .
$(document).ready(function() {
var url = window.location.href;
// As the script executed in iframe, assigning with hardcode value
url = "https://stackoverflow.com/questions/51442637/change-part-of-link-with-part-of-current-url#";
var oldUrl = "https://www.example.com/path/REPLACE/path/path";
var regex = /https:\/\/\w*?\.?\w*?\.\w*?\/\w*?\/(\w*?)\/.*/g;
var match = regex.exec(url);
oldUrl = oldUrl.replace("/REPLACE/", "/" + match[1] + "/");
document.getElementById("mylink").href = oldUrl;
});
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<p>BUTTON</p>
</body>
</html>
EDIT:
I think i have found a solution for this one. Might be a little primitive but inserting it here until someone comes up with a better solution.
Thanks !
<html>
<body onload="makeShort()">
<p id="button" style=display:none; onclick="makeShort()">Click me.</p>
<span id="output" style=display:none; >Wait. Loading....</span>
</body>
<head>
</head>
<script type="text/javascript">
function makeShort()
{
var longUrl=location.href;;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response)
{
if(response.id != null)
{
str =""+response.id+"";
document.getElementById("output").innerHTML = str;
}
else
{
alert("error: creating short url n"+ response.error);
}
});
}
window.onload = makeShort;
function load()
{
//Get your own Browser API Key from https://code.google.com/apis/console/
gapi.client.setApiKey('xxxxxx');
gapi.client.load('urlshortener', 'v1',function(){document.getElementById("output").innerHTML="";});
}
window.onload = load;
</script>
<script>
setTimeout(function(){
document.getElementById('button').click();
},1000);
</script>
<script src="https://apis.google.com/js/client.js"> </script>
</html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<script>
function SendLinkByMail(href) {
var subject= "Interesting Information";
var body = document.getElementById("output").innerHTML;
body += " Interesting Information";
var uri = "mailto:?subject=";
uri += encodeURIComponent(subject);
uri += "&body=";
uri += encodeURIComponent(body);
window.open(uri);
}
</script>
</head>
<body>
<p>Email link to this page</p>
</body>
</html>
Can some one suggest why this "auto-click" function is not working in my code below?
function makeShort() {
var longUrl = location.href;;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response) {
if (response.id != null) {
str = "<b>Long URL:</b>" + longUrl + "<br>";
str += "<b>Short URL:</b> <a href='" + response.id + "'>" + response.id + "</a><br>";
document.getElementById("output").innerHTML = str;
} else {
alert("error: creating short url n" + response.error);
}
});} window.onload = function() {
var button = document.getElementById('modal');
button.form.submit();}
function load() {
//Get your own Browser API Key from https://code.google.com/apis/console/
gapi.client.setApiKey('xxxxxxxxx');
gapi.client.load('urlshortener', 'v1', function() {
document.getElementById("output").innerHTML = "";
});} window.onload = load;
<html>
<input type="button" id="modal" value="Create Short" onclick="makeShort();" /> <br/> <br/>
<div id="output">Wait. Loading....</div>
<head>
</head>
<script src="https://apis.google.com/js/client.js"> </script>
</html>
My basic aim is to insert a "share via email" button on the page which would shorten the url on the address bar and open user's email client/whatsapp app to share that url..
Obviously I could not find a way to combine these two functions in to one since I am not a very experienced js person. The primitive solution I found is to auto-click the first function, get the short url, and then find a different code to insert this in to the body of the "mailto" link, which will be my 2nd challenge.
To programmatically click a button on page load
If you are using jQuery:
$(function() {
$('#modal').click();
});
Plain javascript:
window.onload = function(){
var event = document.createEvent('Event');
event.initEvent('input', true, true);
document.getElementById("modal").dispatchEvent(event);
};
I am running into an error when I attempt to load my website. Whenever I open index.html inside of my browser I get a problem loading page response. The response is confusing because normally I would expect this to show that a file could not load, however my response shows the following:
Firefox can’t find the file at /home/crow/UdacityProjects/mapapp/function (data) { // Setting Self var self = this; this.name = data.name; this.lat = data.lat; this.long = data.long; this.URL = ""; this.street = ""; this.city = ""; this.phone = ""; this.visible = ko.observable(true); // Foursquare URL var foursquareURL = 'https://api.foursquare.com/v2/venues/search?ll=' this.lat ',' this.long '&client_id=' clientID '&client_secret='
It goes on but I've left the rest out for space. As you can see its attempting load my code in the URL, why might this be happening?
I've including my javascript code where the browser seems to be attempting to load the file:
// --- Location information and foursquare URLJSON.
var location = function(data) {
// Setting Self
var self = this;
this.name = data.name;
this.lat = data.lat;
this.long = data.long;
this.URL = "";
this.street = "";
this.city = "";
this.phone = "";
this.visible = ko.observable(true);
This is my index.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Bolton Hill Neighborhood Map</title>
<link rel="stylesheet" href="static/main.css">
<meta name="viewport" content"width=device-width, initial-scale=1">
</head>
<body>
<div class='map'>maps error</div>
<script src="/js/knockout.js"></script>
<script src="/js/jquery.min.js"></script>
<script src="/js/app.js"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&callback=initApp&libraries=places" onerror="errorHandler"></script>
</body>
</html>
My directory structure looks like:
myapp
|
CSS
|
main.css
JS
|
knockout.js
core.js
jquery.min.js
app.js
index.html
I'm not sure what I'm doing wrong here, if anyone could offer me some advice I'd really appreciate it. Thanks!
location is a Javascript keyword. Rename your variable.
I'm doing the FreeCodeCamp course and i'm trying to build a weather app. I found a nice tutorial on how to get the latitude and longitude with geolocation. But now when I try and run the app it doesn't seem to be retrieving the ajax data for me to parse through. I was trying locally and moved it to hosting thinking that might have been it but now I just get a weird error on line one of my html and i don't see anything wrong. Thanks guy here is the code and it's live on weatherapp.boomersplayground.com
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Weather APP</title>
<link rel="stylesheet" href="style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src='script.js'></script>
</head>
<body>
<div id="forecast">
<h1>Weather at <span id="location"> </span></h1>
<!-- <div id="imgdiv">
<img id="img" src=""/> -->
</div>
<p>It is currently <span id="temp"> </span>F with <span id="desc"> </span></p>
<p>Wind: <span id="wind"></span></p>
</div>
</body>
</html>
script.js
$(document).ready(function(){
var Geo = {};
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(success,error);
} else {
alert('Geolocation is not supported');
}
function error(){
alert("That's weird! We couldn't find you!");
}
function success(position){
Geo.lat = position.coords.latitude;
Geo.lng = position.coords.longitude;
}
var key = 'c7e3b3ac66e765aa';
var Weather = "http://api.wunderground.com/api/"+ key +"/geolookup/conditions/q/" + Geo.lat + "," + Geo.lng + ".json";
$.ajax({
url : Weather,
dataType : 'jsonp',
success : function(data) {
var location =data['location']['city'];
var temp = data['current_observation']['temp_f'];
var img = data['current_observation']['icon_url'];
var desc = data['current_observation']['weather'];
var wind = data['current_observation']['wind_string'];
}
})
//setting the spans to the correct parameters
$('#location').html(location);
$('#temp').html(temp);
$('#desc').html(desc);
$('#wind').html(wind);
// filling the image src attribute with the image url
// $('#img').attr('src', img);
});
You use the variables initialised at the AJAX response outside of the success callback. You should use them inside the callback, since they're created asynchronously:
$.ajax({
url : Weather,
dataType : 'jsonp',
success : function(data) {
var location =data['location']['city'];
var temp = data['current_observation']['temp_f'];
var img = data['current_observation']['icon_url'];
var desc = data['current_observation']['weather'];
var wind = data['current_observation']['wind_string'];
$('#location').html(location);
$('#temp').html(temp);
$('#desc').html(desc);
$('#wind').html(wind);
}
});
Because you are treating an Asynchronous call as a synchronous one. The Ajax call needs to be in the success callback of getCurrentPosition. You are building the Ajax url before the at and lng is returned.