I'm trying to auto fill the data in input field which is shown in <div id="demo"></div>. How do I go about doing it?
I tried this but it's not working:
<input id="demo" type="text" />
DEMO: https://jsfiddle.net/z6m3824c/
HTML
<div id="demo"></div>
JS:
var x=document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
x.innerHTML="" + position.coords.latitude +
", " + position.coords.longitude;
}
getLocation()
input field has value.
Try this:
<input id="demo" type="text" onLoad="" />
var x=document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.value="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
x.value="" + position.coords.latitude +
", " + position.coords.longitude;
}
getLocation()
Related
Like the title suggests, I'm trying to allow the user to manually change the javascript coordinate variables in order to get a list of results based off of the coordinates that they entered. I managed to save latitude and longitude into variables which can be plugged into the api key. However I just can't figure out how to adjust those variables from html so that the user can adjust the coords without having to go into the javascript file. I'll attach the relevant code below.
Thanks!
Html
<input id="lat" placeholder="Enter the latitude of your desired hiking location">
<input id="long" placeholder="Enter the longitude of your desired hiking location">
<button value="send" id="submit" onclick="latFunc(); longFunc() ">Search</button>
Javascript
let latitude = "40.2398"
let longitude = "-76.9200"
function latFunc() {
let latitude = document.getElementById("lat").value;
console.log(latitude);
}
function longFunc() {
let longitude = document.getElementById("long").value;
console.log(longitude);
}
latFunc();
longFunc();
$.getJSON("https://www.hikingproject.com/data/get-trails?lat=" + latitude + "&lon=" + longitude + "&maxDistance=10&key=*****************", function (data) {
Have your functions return the value, rather than assigning a variable.
function latFunc() {
return document.getElementById("lat").value;
}
function longFunc() {
return document.getElementById("long").value;
}
When calling the getJSON, use the values by returning value from lat/long inputs. Assuming this code gets executed on a click handler.
$.getJSON("https://www.hikingproject.com/data/get-trails?lat=" + latFunc() + "&lon=" + longFunc() + "&maxDistance=10&key=*****************", function (data) ...
When you initialize, assign your lat/long. You could also encapsulate this into methods.
document.getElementById("lat").value = "40.6";
document.getElementById("long").value = "-75";
Seems like you use jQuery here, here's a complete func handler for click with console to show you the requested URL value.
$("#submit").click(function(e) {
e.preventDefault();
const latitude = $("#lat").val() ;
const longitude =$("#long").val();
console.log(latitude);
console.log(longitude);
var url = "https://www.hikingproject.com/data/get-trails?lat=" + latitude + "&lon=" + longitude + "&maxDistance=10&key=*****************";
console.log(url);
$.getJSON(url, function (data) {
console.log(data);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="lat" value="40.2398" placeholder="Enter the latitude of your desired hiking location">
<input id="long" value="-76.9200" placeholder="Enter the longitude of your desired hiking location">
<button value="send" id="submit">Search</button>
But in case you want to stick with what you have done so far:
function callApi() {
const latitude = document.getElementById("lat").value;
let longitude = document.getElementById("long").value;
console.log("latitude: " + latitude);
console.log("longitude: " + longitude);
var url = "https://www.hikingproject.com/data/get-trails?lat=" + latitude + "&lon=" + longitude + "&maxDistance=10&key=*****************";
console.log(url);
$.getJSON(url, function (data) {
console.log(data);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="lat" placeholder="Enter the latitude of your desired hiking location">
<input id="long" placeholder="Enter the longitude of your desired hiking location">
<button value="send" id="submit" onclick="callApi() ">Search</button>
I am new to HTML, CSS, and JavaScript, so please bear with me.
I am trying to create a form which has an element that uses geolocation to get the current location of a user when user checks a checkbox, and it inputs the coordinates inside a textbox that I've set up. This works fine, but when I uncheck the checkbox, the coordinates disappear along with the textbox.
How do I clear just the coordinates without making the textbox disappear as well?
Below is my code:
function getLocation(myCheck) {
var x = document.getElementById("place");
if (myCheck.checked) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation disabled or unavailable.";
}
function showPosition(position) {
x.innerHTML = position.coords.latitude + ", " + position.coords.longitude;
}
} else {
x.innerHTML = "";
}
}
<h4> Coordinates: <label id="place"><input type="text"></label><label>Use current location? <input id="myCheck" onclick="getLocation(this)" type="checkbox"></label>
</h4>
To empty an input you need to set the value instead of innerHTML. Also note you can avoid creating an input inside the label tag by just using the id & for attribute
function getLocation(myCheck) {
var x = document.getElementById("place");
if (myCheck.checked) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.value = "Geolocation disabled or unavailable.";
}
} else {
x.value = "";
}
}
function showPosition(position) {
x.innerHTML = position.coords.latitude + ", " + position.coords.longitude;
}
<h4> Coordinates: <label for="place">
<input id ="place" type="text"></label>
<label for="myCheck">Use current location?
<input id="myCheck" onclick="getLocation(this)" type="checkbox">
</label>
</h4>
Could you try?
document.getElementById('myCheck').value = "";
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
There's a form on my webpage which is supposed to get the address of the user in a formfield.
When the user clicks allow on the location prompt my purpose is to get the address of the user in an input box in the form.
The prompt comes but this code is unable to fetch the address of the user.
I am looking for something like this
Here's my code
HTML
<form id="contact" action="" method="post" align="center">
<fieldset>
<input placeholder="Your Address" id="address" type="text" tabindex="1" required autofocus>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
</fieldset>
Javascript
<script src="https://code.jquery.com/jquery-1.10.1.js"></script>
<script>
$(document).ready(function () {
var currgeocoder;
//Set geo location lat and long
navigator.geolocation.getCurrentPosition(function (position, html5Error) {
geo_loc = processGeolocationResult(position);
currLatLong = geo_loc.split(",");
initializeCurrent(currLatLong[0], currLatLong[1]);
});
//Get geo location result
function processGeolocationResult(position) {
html5Lat = position.coords.latitude; //Get latitude
html5Lon = position.coords.longitude; //Get longitude
html5TimeStamp = position.timestamp; //Get timestamp
html5Accuracy = position.coords.accuracy; //Get accuracy in meters
return (html5Lat).toFixed(8) + ", " + (html5Lon).toFixed(8);
}
//Check value is present or
function initializeCurrent(latcurr, longcurr) {
currgeocoder = new google.maps.Geocoder();
console.log(latcurr + "-- ######## --" + longcurr);
if (latcurr != '' && longcurr != '') {
//call google api function
var myLatlng = new google.maps.LatLng(latcurr, longcurr);
return getCurrentAddress(myLatlng);
}
}
//Get current address
function getCurrentAddress(location) {
currgeocoder.geocode({
'location': location
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0]);
$("#address").html(results[0].formatted_address);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
});
Try this-
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script type="text/javascript">
$(document).ready(function(){
function getGeoLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
document.getElementById("address").value = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var lat = position.coords.latitude;
var lang = position.coords.longitude;
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lang + "&sensor=true";
$.getJSON(url, function (data) {
var address = data.results[0].formatted_address;
document.getElementById("address").value = address;
});
}
});
</script>
The url http://maps.googleapis.com/maps/api/geocode/json?latlng=22.3545947,91.8128751&sensor=true returns address information in JSON format. You want the "formatted_address" of 0 index inside the "result" index of the JSON.
See the JSON file for more information.
In order to start using Google Maps API, you need to include the Google Maps JS file into your script.
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
You need to replace YOUR_API_KEY with your own key. You need to generate one for your application.
Get API Key
There is another issue in your code at this line.
$("#address").html(results[0].formatted_address);
The element with id="address" is an input field, so the .html() function is not available on it. You need to use the .val() function. So you can replace that line with the one below.
$("#address").val(results[0].formatted_address);
This should get your code working.
The reason your textfield is not being populated with the address is because of this line in your code:
In "getCurrentAddress" function:
$("#address").html(results[0].formatted_address);
The problem, in this line is that you want to set an input "textfield". In this case you cannot do .html()
You can fix this by changing it to:
$("#address").val(results[0].formatted_address);
Take a look at the following fiddle:
https://jsfiddle.net/ezr6z7so/
I have got the current location with complete address and shown this in a <span> by ID. But i want to show this address in input type text also. My current code is
<script type="text/javascript">
var positionlatitude;
var positionlongitude;
var address;
google.maps.event.addDomListener(window, 'load', function () {
var places = new google.maps.places.Autocomplete(document.getElementById('location_#item.Name'));
google.maps.event.addListener(places, 'place_changed', function () {
var place = places.getPlace();
address = place.formatted_address;
positionlatitude = place.geometry.location.lat();
positionlongitude = place.geometry.location.lng();
});
});
navigator.geolocation.getCurrentPosition(success);
function success(position) {
var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
$.getJSON(GEOCODING).done(function (location) {
$('span[id^="address"]').html(location.results[0].formatted_address);
})
}
</script>
<label for="location">Your Location: </label><br />
<span id="address" class="input-form" ></span>
<input type="text" value="" name="address" id="geolocation"/>
Thanks To everyone If you consider this question.
now i got the answer.
document.getElementById("geolocation").value = location.results[0].formatted_address;
<input type="hidden" value="" name="address" id="geolocation"/>
This will set the address in input type hidden
I have a form that submits a location to Google's Geocoder and returns the lat/long and changes the map. If I use ng-click on the icon it doesn't work unless I click on it twice. If I use ng-submit on the form it appends to the url and doesn't perform the task. I feel like I'm close to getting this to work but I'm lost as to what I'm doing wrong.
Below is the form
<li>
<form action="" class="search-form" ng-submit="convertLatLonToAddress()">
<div class="form-group has-feedback">
<label for="search" class="sr-only">Search</label>
<input type="text" class="form-control" name="search" id="search" placeholder="Search for an address or place name">
<i class="fa fa-search form-control-indicator"></i>
</div>
</form>
</li>
And here is the function
$scope.convertLatLonToAddress = function(){
var address = $('#search').val();
var geocoder = new google.maps.Geocoder();
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();
// console.log(latitude + ' and ' + longitude);
$scope.center.lat = latitude;
$scope.center.lon = longitude;
}
});
};
Thanks to #PSL it's fixed! See below:
<li>
<form class="search-form" ng-submit="convertLatLonToAddress(searchText)">
<div class="form-group has-feedback">
<label for="search" class="sr-only">Search</label>
<input type="text" class="form-control" name="search" id="search" placeholder="Search for an address or place name" ng-model="searchText">
<button style="visibility: hidden"></button>
<a ng-click="convertLatLonToAddress(searchText)">
<i class="fa fa-search form-control-indicator"></i>
</a>
</div>
</form>
</li>
And
$scope.convertLatLonToAddress = function(searchText){
// var address = $('#search').val();
var address = searchText;
var geocoder = new google.maps.Geocoder();
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();
// console.log(latitude + ' and ' + longitude);
$scope.center.lat = latitude;
$scope.center.lon = longitude;
$scope.$apply();
}
});
};
You need to invoke the digest cycle manually inside the async call of geocode, since geocode does not run inside angular context.
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();
// console.log(latitude + ' and ' + longitude);
$scope.center.lat = latitude;
$scope.center.lon = longitude;
$scope.$apply();
}
});
Everytime you click, ng-click triggers the digest cycle so previous cycle runs the non angular async call and updated scope which angular is unaware, when you click on it again it runs the digest cycle again and does the same but that time the values you set previously will be picked and that is why it takes 2 clicks. For ng-submit to execute you need a form element trigger, ex: a button or input type="submit" that causes submit behavior to happen on the form. You should also remove action from form unless you really intend to do a redirection.
Apart from that you can use ng-model on the textbox and pass the value to your function as well instead of getting value from DOM directly.
<input type="text" class="form-control" name="search" id="search" placeholder="Search for an address or place name" ng-model="searchText">
and pass the value via ng-click as ng-click="convertLatLonToAddress(searchText)" and use it inside your function.
In order to avoid scope.apply(); in your controller you could abstract out geoCoder to an angular service and return a promise (creating deferred object) and use that service in your controller.
myApp.service('geoCoderService', ['$q', function($q){
this.getCoordinates = function(address){
var defer = $q.defer();
var geocoder = new google.maps.Geocoder();
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();
return defer.resolve({latitude :latitude , longitude :longitude });
}
//faliure
defer.reject(status);
});
return defer.promise;
}
});
inject geoCoderService and get data using:
geoCoderService.getCoordinates(address).then(function(coordinates){
//populate it
}).catch(function(errorStatus){ /*ooops Error*/ })
Try this
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.convertLatLonToAddress = function() {
var address = $('#search').val();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$scope.lat = results[0].geometry.location.lat();
$scope.lon = results[0].geometry.location.lng();
console.log($scope.lat + ' and ' + $scope.lon);
setTimeout(function(){$scope.$apply();},0)
}
});
};
});
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<li>
<div class="form-group has-feedback">
<label for="search" class="sr-only">Search</label>
<input type="text" class="form-control" name="search" id="search" placeholder="Search for an address or place name">
<i class="fa fa-search form-control-indicator"></i>
<button ng-click="convertLatLonToAddress()">Click</button>
<br>
Lat : <input type="text" ng-model="lat"><br>
Lon : <input type="text" ng-model="lon">
</div>
</li>
</div>
</body>