How to use variable in another file? - javascript

I want to pass an variable to another file. I use the lat variable in new js file but not working.
In address.php:
<div class="saveaddress">Click me</div>
<script>
var lat;
var lng;
function displayLocation(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
}
</script>
.
.
.
<script src="js/save.js"></script>
save.js file:
$('.saveaddress').click(function(){
alert(lat);
}
How can I do that? (How can I do that? (I followed other questions but not worked for me.)

You should try fixing the scope of the variable by not redclaring:
var lat;
var lng;
function displayLocation(position) {
lat = position.coords.latitude;
lng = position.coords.longitude;
}
Alternatively, you could add the variable to the window:
function displayLocation(position) {
window.lat = position.coords.latitude;
window.lng = position.coords.longitude;
}
Then:
$('.saveaddress').click(function(){
alert(window.lat);
}

remove the two var inside the displayLocation function

Related

how to fix. [Deprecation] getCurrentPosition() and watchPosition() no longer work on insecure origins.

I got one console error when i try to run the code in my temp server "[Deprecation] getCurrentPosition() and watchPosition() no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS".
in my header am linking the script tag.
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBlS6vRUDeM0XdliZ4iWDyDMekH45wYcck&libraries=places" type="text/javascript"></script>
Get your current position:
Click here
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
document.getElementById("start").value = "";
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
document.getElementById('cityLat').value = position.coords.latitude;
document.getElementById('cityLng').value = position.coords.longitude;
}
</script>
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var bangalore = new google.maps.LatLng(12.9716, 77.5946);
var myOptions = {
zoom:12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: bangalore
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var startLat = document.getElementById('cityLat').value;
var startLong = document.getElementById('cityLng').value;
var endLat = $('select.end').find(':selected').data('lat');
var endLong = $('select.end').find(':selected').data('long');
/*alert(startLat+"---"+startLong+"---"+endLat+"---"+endLong);*/
if(startLat && startLong){
var start = new google.maps.LatLng(startLat, startLong);
}else{
var start = document.getElementById("start").value;
}
var end = new google.maps.LatLng(endLat, endLong);
var distanceInput = document.getElementById("distance");
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
distanceInput.value = response.routes[0].legs[0].distance.value / 1000;
}
});
}
</script>
when i run the above code snippet in my local system i getting the map correctly.
when i move the code to testing server am getting the console error "[Deprecation] getCurrentPosition() and watchPosition() no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS"
I tried without https the script tag source link.
Anybody could you please give me a suggestion for this ?
Thank you.
You need to install SSL Certificate. There is no quick fix for this solution. Google Chrome and other browsers are blocking this for security reasons.
Chrome has disallowed the usage of getCurrentPosition() for websites without SSL.
Google Maps API could solve this but its usage limits is way low.

using ajax to post js variables to php

Hey guys I have geolocation.html file and test.php file. I am using Ajax to pass var longitude and latitude from geolocation.html to my test.php for processing but it is showing me blank pages. I don't know why? Please help
geolocation.html
<html>
<head>
<script type= "text/javascript" src= "js/jquery.js" > </script>
<script>
//javascript is on the client
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
document.write("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
//Pass longitude and latitude to php how?
$.ajax({
type: 'POST',
url: 'test.php',
data: {lat: latitude,
lng:longitude}
});
}
</head>
Then my test.php
<?php
// $addlat = $_GET['addlat'];
// $addlong = $_GET['addlong'];
if (isset($_POST['lat']) && isset($_POST['lng']) ) {
$lat = $_POST['lat'];
$lng = $_POST['lng'];
echo $lat." ".$lng ;
}
?>
I modified your geolocation.html file. Hope this will help!
<html>
<head>
//ajax lib file
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
//javascript is on the client
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
document.write("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
//Pass longitude and latitude to php how?
$.post("test.php",
{
lat: latitude,
lng: longitude
},
function(data){
alert(data);
});
}
</script>
</head>
<button onclick="getLocation();">GET LOCATION</button>

Geolocation api javascript

I try to alert my latitude and longitude, but it's doesn't work.
I create a global variables, and change this variables in function. I my other functions not sees this global variables. I don't know, what is the error.
var latitdue;
var longitude;
navigator.geolocation.getCurrentPosition(
function coords(position) {
longitude = position.coords.longitude;
latitude = position.coords.latitude;
}, function (error) {
alert("Error: " + error.code);
},
{
enableHighAccuracy : false,
timeout : 10000,
maximumAge : 1000
});
function a(){
alert(longitude, latitude);
}
a();
its a typo error "latitude" not var latitdue
change
var latitdue;
to
var latitude
and "Allow" the popup or hint on browser bar for accessing computer's location
Try the below code:
<script type="text/javascript">
var latitude;
var longitude;
function a(){
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(
function coords(position) {
longitude = position.coords.longitude;
latitude = position.coords.latitude;
alert("Lat Long is : " + longitude +"," + latitude);
}, function (error) {
alert("Error: " + error.code);
},
{
enableHighAccuracy : true,
timeout : 10000,
maximumAge : 1000
});
}
else
{
alert ("GEOLOCATION NOT SUPPORTED....");
}
}
//a();
</script>
</head>
<body onLoad="a();">
TESTING GEOLOCATION
</body>
You will have to call the method after loading success.
Also, Allow for share location.

Why does my variables dont take the value in the function?

I want to display on screen the var longitude en latitude but I think that the function is executing last and I'am stuck with the initial values.
The objective is to print on screen the exact values of the geolocation that the browser returns.
Thanks !!!
<!DOCTYPE html>
<head>
<script>
var longitude = "10";
var latitude = "20";
</script>
</head>
<html>
<body onload="getLocation()">
<script>
var longitude = "30";
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
latitude = position.coords.latitude;
longitude = position.coords.longitude;
alert('aaab:' +longitude);
});
}else {
alert("Geolocation API is not supported in your browser.");
}
}
</script>
<script>
alert("ccc");
document.write (longitude);
document.write (latitude);
</script>
</body>
</html>
i know that it's working within the function, but there is any way to use those variable outside? I just want to be able to store them in one global variable that cand be called wherever. Thanks
document.write is being executed before your code that updates it is being run. You need to do the document.write in the callback like so:
<!DOCTYPE html>
<head>
<script type='text/javascript'>
var longitude = "10";
var latitude = "20";
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
latitude = position.coords.latitude;
longitude = position.coords.longitude;
document.write(latitude+" / "+longitude);
});
}else{
alert("Geolocation API is not supported in your browser.");
}
}
</script>
</head>
<body onload="getLocation()">
</body>
</html>
Try this:
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayLocation);
}else {
alert("Geolocation API is not supported in your browser.");
}
}
function displayLocation(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
alert('aaab:' +longitude);
}
The Geolocation Callback probably hasn't been called at the time you write your longitude and latitude. Maybe you can use jQuery to write the correct values to the screen...
<script>
var longitude = "30";
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
latitude = position.coords.latitude;
longitude = position.coords.longitude;
//alert('aaab:' +longitude);
// Use jQuery to write your values to the html
$("#longitude").html(longitude);
$("#latitude").html(latitude);
});
}else {
alert("Geolocation API is not supported in your browser.");
}
}
</script>
<html>
...
<body onload="getLocation()">
<div id="longitude"></div>
<div id="latitude"></div>
</body>
</html>

Google Map - Current location

I would like to get the address string of the current user location. Is that possible?
Many thanks.
Regards
the user's location is available in google.loader.ClientLocation (this will contain a guess based on the client IP if the IP is known)
google.loader.ClientLocation
When an application makes use of the
AJAX API loader, the loader attempts
to geo locate the client based on its
IP address. If this process succeeds,
the client's location, scoped to the
metro level, is made available in the
google.loader.ClientLocation property.
If the process fails to find a match,
this property is set to null.
http://code.google.com/apis/ajax/documentation/#ClientLocation
if you are trying to get The Street Address!
include both JS and MAP Api Key, keep all together from the wizard
my code look like this: (use also a bit of jQuery)
var geocoder = null;
var lat = null;
var lng = null;
$(function() {
if (GBrowserIsCompatible()) {
if (google.loader.ClientLocation &&
// i used this here cause not always
//this retrieve the correct LAT & LON
// so set it manually
google.loader.ClientLocation.address.country_code == "IT" ) {
lat = google.loader.ClientLocation.latitude;
lng = google.loader.ClientLocation.longitude;
} else {
//alert( 'Insert Your Latitude & longitude manually!' );
lat = '42.464826';
lng = '14.214095';
}
//creat the full LAT + LON
points = new GLatLng( lat , lng );
//get the Street Address
get_address(points);
}
});
function get_address(latlng) {
if (latlng) {
geocoder = new GClientGeocoder();
geocoder.getLocations(latlng, function(addresses) {
if(addresses.Status.code != 200) {
alert("reverse geocoder failed to find an address for " + latlng.toUrlValue());
}
else {
address = addresses.Placemark[0];
var myHtml = address.address;
$('#address').text(myHtml);
}
});
}
};
peraphs read this link may help too:
Get street address at lat/long pair
If you need something more precise than IP geolocation, you could use the W3C Geolocation API in supported browsers (notably, Firefox 3.5 and Mobile Safari) to request the user's latitude and longitude and then use Google's client-side reverse geocoding service to guess the user's approximate street address. (Code samples for both of those steps included on my test page.)
If you go this route, be sure to explain to your users up front why you're requesting their location and how you're using their information (e.g. that you're not storing it until they actually submit a form) because it's technically required by the API and because some users will be creeped out by how easily you can guess their street address.
Yes it is possible achieve using html 5 and Google API 3, in the given code you have to change your APIKey and map-canvas is a element in the html body
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=yourAPIKey&sensor=false"></script>
<script type="text/javascript">
var lat;
var lng;
function initialize() {
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function showPosition(position)
{
lat = position.coords.latitude;
lng = position.coords.longitude;
var myLatlng = new google.maps.LatLng(lat, lng);
var myTittle = "My Current Location! Lat: " + lat + "lng: " + lng;
var marker = new google.maps.Marker({
position: myLatlng,
title: myTittle
});
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I was looking to find how to map the current location and a destination location. To achieve this here is what I did:
Note* replace: YOUR_DESTINATION_ADDRESS with an address in a format like: "147+Wyndham+Street+N+,+Suite+206,+Guelph,+On,+N1H+4E9"
<div id="Map" style="width: 100%; height: 600px;"> </div>
<script type="text/javascript">
$(function(){
var zoom = 11;
function success(position) {
var LAT = position.coords.latitude;
var LONG = position.coords.longitude;
$('#Map').append('<p>Current Latitude: ' + LAT + '<br/>Current Logitude: ' + LONG +'<br/><br/>Note* This may not display your exact location, but just your city. Works better on mobile devices</p>');
var map = '<iframe style="width: 100%; height: 600px;" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.ca/maps?source=s_d&saddr=' + LAT +',+' + LONG +'&daddr=**YOUR_DESTINATION_ADDRESS**&ie=UTF8&t=hz=' + zoom + '&output=embed"></iframe>';
$('#Map').append(map);
}
function error(){
/*Error Code*/
}
function MakeMap(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
}
}
MakeMap();
});
</script>

Categories