Get location from JavaScript and pass it to PHP - php

I want to get the longitude and latitude using javascript, and than to compare it with the previous location. Something like Facebook does when you log in from another computer, but much more simplified. In order to achieve this I have created 2 hidden fields and when the user submits the form the values are to be sent to the server.
<body>
<p id="log">Login to continue:
<form action="welcome.php" method="post">
Username: <input type="text" name="user" required >
Password: <input type="password" required>
<input type="hidden" name= "longitude" id="longitude">
<input type= "hidden" name ="latitude" id="latitude">
<input type="submit" name="submit" onclick="getLocation()">
</p>
<script>
var x=document.getElementById("log");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
document.getElementByID("longitude").value = longitude;
document.getElementByID("latitude").value = latitude;
}
</script>
But in welcome.php the code :
$latitude=$_POST["latitude"];
$longtude=$_POST["longitude"];
returns :
Notice: Undefined index: latitude in C:\xampp\htdocs\welcome.php on line 8
Notice: Undefined index: longitude in C:\xampp\htdocs\welcome.php on line 9
Is there better way to do this, and how to fix this?

You are trying to access the elements by ID, but they have no ID.
Either add an ID attribute to them, or reference them in a different way.

you have made mistake on document.getElementByID the d should be small ie document.getElementById

Change this
function showPosition(position)
{
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
document.getElementByID("longitude").value = longitude;
document.getElementByID("latitude").value = latitude;
}
to this
function showPosition(position)
{
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
document.getElementById("longitude").value = longitude;
document.getElementById("latitude").value = latitude;
}
And it should work

Open firebug, click on label network and take a look into the post request if parameters langitude and longitude have been sent. If yes, the failure must be in your php script. If you cant't find both parameters, check your client code.

Related

how to use Google place autocomplete without google ui?

enter image description hereI am new to Api stuff. I want to achieve following which I did. But I want to show list of places without using google UI. And from the list, clicked address should be in the form. How can I do that? Is there any example code that I can use, would be great.
Google place autocomplete
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key='******************'&libraries=places"></script>
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', function () {
var places = new google.maps.places.Autocomplete(document.getElementById('txtPlaces'));
google.maps.event.addListener(places, 'place_changed', function () {
var place = places.getPlace();
var address = place.formatted_address;
var latitude = place.geometry.location.A;
var longitude = place.geometry.location.F;
var mesg = "Address: " + address;
mesg += "\nLatitude: " + latitude;
mesg += "\nLongitude: " + longitude;
alert(mesg);
});
});
</script>
<span>Location:</span>
<input type="text" id="txtPlaces" style="width: 250px" placeholder="Enter a location" />

Passing data from JS to PHP is not working

I have an autocomplete googleapis that gets, latitude, longitude and adress correctly. When I try to pass these values to PHP, my ignorance of Java is making me do something wrong because php is not receiving any data.
JS
<h1>Autocomplete form</h1>
<input id="searchMapInput" class="mapControls" type="text" placeholder="- Type your location here -">
<ul id="geoData">
<li>Full Address: <span id="location-snap"></span></li>
<li>Latitude: <span id="lat-span"></span></li>
<li>Longitude: <span id="lon-span"></span></li>
</ul>
<script>
function initMap() {
var input = document.getElementById('searchMapInput');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
document.getElementById('location-snap').innerHTML = place.formatted_address;
document.getElementById('lat-span').innerHTML = place.geometry.location.lat();
document.getElementById('lon-span').innerHTML = place.geometry.location.lng();
function redirectToPosition(position) {
window.location='a.php?lat='+place.geometry.location.lat+'&long='+place.geometry.location.lng;
}
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=[API_KEY_goes here]&libraries=places&callback=initMap" async defer>
</script>
And the serverside PHP is this (edited after comments)
<?php
$latitude = (isset($_GET['lat']))?$_GET['lat']:'';
$longitude = (isset($_GET['long']))?$_GET['long']:'';
echo "Latitude:".$latitude."</br>";
echo "Longitude:".$longitude;
?>
I get the url
---/a.php?lat=function%20(){return%20a}&long=function%20(){return%20b}
and the following echos:
Latitude: function (){return a}
Longitude: function (){return b}
You should check $_GET['lat'] and $_GET['long']
<?php
$latitude = (isset($_GET['lat']))?$_GET['lat']:'';
$longitude = (isset($_GET['long']))?$_GET['long']:'';
echo "Latitude:".$latitude."</br>";
echo "longitude:".$longitude;
?>

How to pass div id value to PHP variable?

I am using an auto complete form to find "lat" and "lng" for a city name and it works fine. I get the correct values in div id="lat" and div id="lng" but I want to use these values in php variables as $latitude="lat" and $longitude="lng" to use them in a php script that needs $latitude and $longitude?
I have been trying many of the solutions presented here, but my knowledge is too short to make it work.
The script is:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=MY_KEY&libraries=places">
</script>
<script>
function initialize() {
var address = (document.getElementById('city-input'));
var autocomplete = new google.maps.places.Autocomplete(address);
autocomplete.setTypes(['geocode']);
google.maps.event.addListener(autocomplete, 'place_changed', function()
{
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
var address = '';
if (place.address_components) {
address = [
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
document.getElementById('lat').innerHTML = place.geometry.location.lat();
document.getElementById('lng').innerHTML = place.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<input id="city-input" class="controls" type="text"
placeholder="Enter a location">
<div id="lat"></div>
<div id="lng"></div>
And for the php part I am trying this with no result at all
<?php
$latitude = (isset($_GET['lat']))?$_GET['lat']:'';
$longitude = (isset($_GET['lng']))?$_GET['lng']:'';
echo $latitude;
echo $longitude;
?>
Is there any way to do what I intend to do? (get $latitude and $longitude with the values that were correctly obtained from googleapis?)
Thank you so much for any precious help :-)
I am sorry for confusing vanialla JS with jquery. But I'm trying my best to help.
You can do it using ajax
get the lat value and long value and pass it to ajax data. lets call it
latjs and lonjs
$.ajax({
type: "POST",
url: "lat_lon.php",
data: "lat="+latjs+"&lon="+lonjs,
success: function (html) {
if (html === 'true') {
at the php side, capture it this way:
$data = file_get_contents('php://input');
if($data != null) {
parse_str($data, $output);
$output_lan = $output['lat'];
$output_lon = $output['lon'];
blah blah process
}
The last 2 assignment code is wrong:
document.getElementById('lat').innerHTML = place.geometry.location.lat();
document.getElementById('long').innerHTML = place.geometry.location.lng();
The above should be
$("#lat").html(place.geometry.location.lat());
$("#long").html(place.geometry.location.lng());
the code is not 100% working, but should be in the above lines. no need to use get elementbyID and all.
Hope this helps
VInay KR

I want to get latitude and longitude from Autocomplete Address Form

I'm trying to save latitude and longitude by autocomplete Google Maps, but I can't make this work. I don't know how to use Google Maps Api. I need to add 2 fields with longitude and latitude, and when I select my address from my input, these 2 fields ( longitude and latitude ) should be filled with the correct values.
What I have tried so far:
Google map api get Latitude and longitude from autocomplete without map
Here is my script
<script>
// This sample uses the Autocomplete widget to help the user select a
// place, then it retrieves the address components associated with that
// place, and then it populates the form fields with those details.
// This sample requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script
// src="https://maps.googleapis.com/maps/api/js?key=MY_API&libraries=places">
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
function initAutocomplete() {
// Create the autocomplete object, restricting the search predictions to
// geographical location types.
autocomplete = new google.maps.places.Autocomplete(
document.getElementById('autocomplete'), {types: ['geocode']});
// Avoid paying for data that you don't need by restricting the set of
// place fields that are returned to just the address components.
autocomplete.setFields(['address_component']);
// When the user selects an address from the drop-down, populate the
// address fields in the form.
autocomplete.addListener('place_changed', fillInAddress);
}
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details,
// and then fill-in the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle(
{center: geolocation, radius: position.coords.accuracy});
autocomplete.setBounds(circle.getBounds());
});
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=MY_API&libraries=places&callback=initAutocomplete"
async defer></script>
Here is my view
<div class="form-group col-md-4" style="left: 10px;position: relative" id="locationField">
<label class="label" for="jobs">
Address
</label>
<div class="input-group">
<div class="input-group-addon" style="border-color: #bbb">
<i class="icon-hotel-restaurant-235 u-line-icon-pro"></i>
</div>
<label class="input" style="height: 28px">
<input id="autocomplete"
placeholder="Enter your address"
onFocus="geolocate()"
type="text"
style="height: 33px"
name="address"/> </label>
</div>
</div>
I have written this script for one of my recent project this works fine for me
<script>
var autocomplete;
function initAutocomplete(){
autocomplete = new google.maps.places.Autocomplete(
document.getElementById('autocomplete-input'), {types: ['geocode']});
autocomplete.addListener('place_changed', getAddressDetails);
}
function getAddressDetails(){
var place = autocomplete.getPlace();
window.lat = place.geometry.location.lat();
window.long = place.geometry.location.lng();
}
function geolocate(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle(
{center: geolocation, radius: position.coords.accuracy});
autocomplete.setBounds(circle.getBounds());
});
}
}
</script>
This will be your input
<div id="autocomplete-container">
<input id="autocomplete-input" type="text"
class="autocomplete" autocomplete="off" spellcheck="false" dir="auto"
placeholder="Location" onFocus="geolocate()">
</div>
This code works fine for my projects
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
var lat = place.geometry.location.lat();
var lng = place.geometry.location.lng();
var placeId = place.place_id;
// to set city name, using the locality param
var componentForm = {
locality: 'short_name',
};
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById("city").value = val;
}
}
document.getElementById("latitude").value = lat;
document.getElementById("longitude").value = lng;
document.getElementById("location_id").value = placeId;
});

Google maps api will not return coordinates on submit

I try to describe my issue as easy as possible..
When I submit a form, I need to call another function. I tried onSubmit, but unfortunately it doesnot work properly, as the function that I need to call is Google Maps API matter getting coordinates from textbox where a user is choosing the location.. The function is never called or it seems that it is called too late.. So I tried this:
<input type="button" value="Search" name="submitBtn" id="subBtn1" onclick="onSubmit1();">
and function onSubmit1() is as following:
function onSubmit1 () {
codeAddress();
// document.forms["searchForm"].submit();
}
After clicking the button, the function works.. codeAddress gets me the latitude and longitude from Google servers and pre-fills them to textboxes in my searchForm.
However, if I remove the doble slash and want to submit the form, the following happens:
form is submitted, but the latitude and longitude is always empty strings..
Any ideas.. Is it possible, that the second line in onSubmit1 function just doesnot wait for goole to do its job?
Thanks for any tips..
Please know, that the form and all its functions work perfectly if I for example set the coordinates by myself and submit the form then.. There is no problem in that
EDIT
function codeAddress() {
geocoder = new google.maps.Geocoder();
var address = document.getElementById("my-address").value;
geocoder.geocode(
{ 'address': address},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
document.getElementById("my-lat").value = lat;
document.getElementById("my-lng").value = lng;
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
});
}
Your issue is that codeAddress is asynchronous (well the geocode method of the geocoder object is), and therefor returns immediately.
What you must do is only submit the form in the async callback:
function codeAddress() {
geocoder = new google.maps.Geocoder();
var address = document.getElementById("my-address").value;
geocoder.geocode(
{ 'address': address},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
document.getElementById("my-lat").value = lat;
document.getElementById("my-lng").value = lng;
//now submit form
document.forms["searchForm"].submit();
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
});
}

Categories