Get current position into PHP variable

I like to store user’s current position as address inside variable and further manipulate. How to store this value outside Javascript into PHP variable using input or PHP variable:
This is just example:

Value is inside Javascript:+ position.coords.latitude


       (function() {

            if(!!navigator.geolocation) {

                var map;

                var mapOptions = {
                    zoom: 15,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                
                map = new google.maps.Map(document.getElementById('google_canvas'), mapOptions);
            
                navigator.geolocation.getCurrentPosition(function(position) {

                    var geolocate = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                    
                    var infowindow = new google.maps.InfoWindow({
                        map: map,
                        position: geolocate,
                        content:
                            '<h1>Location pinned from HTML5 Geolocation!</h1>' +
                            '<h2>Latitude: ' + position.coords.latitude + '</h2>' +
                            '<h2>Longitude: ' + position.coords.longitude + '</h2>'
                    });

                    map.setCenter(geolocate);

                });

            } else {
                document.getElementById('google_canvas').innerHTML = 'No Geolocation Support.';
            }

        })();  

For HTML 5 you can set a data atrr inside the h2 element Eg.

<h2 data-latitude="<?php echo $phpVariable ?>" id="latitude"></h2>

So then you can manipulate the data-latitude via js code as you want.

var latitude=document.getElementById('latitude');

//to output the value in the data-latitude atrr write as below line

console.log(latitude.dataset.latitude);

Check the console.

I’m new to this.

I have tested.

var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var latitude=document.getElementById('latitude');
var longitude=document.getElementById('longitude');

and

<h2 data-latitude="latitude" id="latitude"></h2>
<h2 data-longitude="longitude" id="longitude"></h2>

Is this the correct one? H1 and H2 will be blank but Google map and its current location will be shown. I’m not sure.

If you want to retrieve and manipulate the data-latitude then you must assign to a variable.Eg.

var latitudeVariable=latitude.dataset.latitude;

I have set all code. Please confirm if there is any mistake.


(function()
 {

  var outputlat = document.getElementById('latitude');
  var outputlng = document.getElementById('longitude');

  var outputlat = latitude.dataset.gmap;
  var outputlng = longitude.dataset.gmap;

  if(!!navigator.geolocation) {

   var map;

   var mapOptions = {
   zoom: 15,
   mapTypeId: google.maps.MapTypeId.ROADMAP
   };

   map = new google.maps.Map(document.getElementById('google_canvas'), mapOptions);

   navigator.geolocation.getCurrentPosition(function(position)
    {

     var geolocate = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

     var infowindow = new google.maps.InfoWindow(
      {
      map: map,
      position: geolocate,
      content:
       '<h1>Location pinned from HTML5 Geolocation!</h1>' +
       '<h2>Latitude: ' + position.coords.latitude + '</h2>' +
       '<h2>Longitude: ' + position.coords.longitude + '</h2>'
      }
     );

     map.setCenter(geolocate);

    }
   );

  } else {
   document.getElementById('google_canvas').innerHTML = 'No Geolocation Support.';
  }

 }
)();

Showing values inside H2 or PHP variable:

<h2 data-gmap="outputlat" id="myoutputlatitude"></h2>
<h2 data-gmap="outputlng" id="myoutputlongitude"></h2>
<?php

echo '$outputlat':
echo '$outputlng':

?>

The coordinates are you going to retrieve via php variable or javascript? I mean that you are going to echo into the h2 element or set these via js function inside the element attr?Eg.

<h2 data-gmap="<?phpecho '$outputlat;?>'" id="myoutputlatitude"></h2>

or

<h2 data-gmap="function (returns the lat);" id="myoutputlatitude"></h2>

I have never done this.Sorry.

Geo values should be fetched via Gmap API. When I get these values I store these values inside WP or any other application using variables $outputlat and and values $outputlng.

If I understand we fetch values using
var outputlat = document.getElementById(‘latitude’);
var outputlng = document.getElementById(‘longitude’);
and also
navigator.geolocation.getCurrentPosition(function(position)

Than we set dataset names and their ID gmap:
var outputlat = latitude.dataset.gmap;
var outputlng = longitude.dataset.gmap;

data-gmap=“outputlat” and data-gmap=“outputlng” will connect Javascript vales into PHP variables.

<?php

echo '$outputlat':
echo '$outputlng':

?>

Code is just idea and it is wrong. I kindly ask you to post the whole code to test these variables.

Ok I think that understand now:
There are some ways to pass javascript variables in to php variable…Some of them:

  1. send the information in a form as stated here, (will result in a page refresh)
  2. pass it in ajax (several posts on here about that) (without a page refresh)
  3. make a http request via a XMLHttpRequest request (without a page refresh)

I suggest you to make two input elements to set the js values (lat &lon) in your page:

<input type="text" name="latitude"  id="latitude">
<input type="text" name="longitude" id="longitude">

And add them the js values as you took from API.

(function()
 {

  var outputlat = document.getElementById('latitude');
  var outputlng = document.getElementById('longitude');
 
  if(!!navigator.geolocation) {

   var map;

   var mapOptions = {
   zoom: 15,
   mapTypeId: google.maps.MapTypeId.ROADMAP
   };

   map = new google.maps.Map(document.getElementById('google_canvas'), mapOptions);

   navigator.geolocation.getCurrentPosition(function(position)
    {

     var geolocate = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
     
     outputlat.value=position.coords.latitude;
     outputlng.value=position.coords.longitude;
     var infowindow = new google.maps.InfoWindow(
      {
      map: map,
      position: geolocate,
      content:
       '<h1>Location pinned from HTML5 Geolocation!</h1>' +
       '<h2>Latitude: ' + position.coords.latitude + '</h2>' +
       '<h2>Longitude: ' + position.coords.longitude + '</h2>'
      }
     );

     map.setCenter(geolocate);

    }
   );

  } else {
   document.getElementById('google_canvas').innerHTML = 'No Geolocation Support.';
  }

 }
)();

Now you can take these values via php as following

<?php
$outputlat=$_POST['latitude'];
$outputlng=$_POST['longitude'];
?>

Of course the input element must be inside a form element and when submit the form then the values of the php variables are able to pass into server database.

<form action="" method="post">
<input type="text" name="latitude"  id="latitude" placeholder="latitude">
<input type="text" name="longitude" id="longitude" placeholder="longitude">
<button type="submit">SUBMIT</button>
</form>

Thank you for all replies. Please check if this is without mistake and variable names.
If I further develop your suggestion, this will work using attributes and dataset:

Javascript:

var outputlat = document.getElementById('latitude');
var outputlng = document.getElementById('longitude');
var outputlat1 = latitude.dataset.gmap;//Added lines
var outputlng1 = longitude.dataset.gmap;//Added lines

PHP code:

$smarty->assign("myoutputlat2", $_REQUEST['latitude']);
$smarty->assign("myoutputlng2", $_REQUEST['longitude']);

HTML code:

//echo stored varriables
{$myoutputlat2}
{$myoutputlng2}
<input data-gmap="outputlat1" name="outputlat1" readonly />
<input data-gmap="outputlng1" name="outputlng1" readonly />

I think it’s ok. Do you have errors?

ReferenceError: latitude is not defined
Line: var outputlat1 = latitude.dataset.gmap;//Added lines

To see if you have problem with php or javascript set in the input element a value and then check the console.If you don;t have errors that means php problem.

<input data-gmap=123456 name="outputlat1" readonly />
<input data-gmap=654321 name="outputlng1" readonly />

I have tried also on working example. Please check this working example:
clat and clng will not be shown. Source is:
http://fiddle.jshell.net/Cxfsx/44/


<!DOCTYPE html>
<html>
<head>

<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta charset="UTF-8" />

<title>Watch position</title>

<style type="text/css">
<!--
#container {
 padding:1em;
 font-size:1.5em;
}

label {
 display:block;
 margin-top:12px;
}
-->
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap" async defer></script>

</head>

<body>



<div id="container">


<h1>Watch Position</h1>


<section>


<input type="button" id="startWatchButton" value="Watch Location" />
<input type="button" id="clearWatchButton" value="Stop" />

<a href="" id="mapLink" target="_blank">View Map</a>

<label for="clat">Latitude:</label>
<input type="text" id="clat" name="clat" />

<label for="clng">Longitude:</label>
<input type="text" id="clng" name="clng" />

<label for="calt">Altitude</label>
<input type="text" id="calt" name="calt" />

<label for="cacc">Accuracy</label>
<input type="text" id="cacc" name="cacc" />

<label for="caltAcc">Altitude Accuracy</label>
<input type="text" id="caltAcc" name="caltAcc" />

<label for="cheading">Heading</label>
<input type="text" id="cheading" name="cheading" />

<label for="cspeed">Speed</label>
<input type="text" id="cspeed" name="cspeed" />

<label for="ctimestamp">Timestamp</label>
<input type="text" id="ctimestamp" name="ctimestamp" />

<input type="hidden" data-decoder="clat" type="text" name="clat" id="latitude" readonly />
<input type="hidden" data-decoder="clng" type="text" name="clng" id="longitude" readonly />



<p><label class="text_form1">Longitude:</label><input data-decoder="clat" type="text" name="clat" readonly /></p>
<p><label class="text_form1">Latitude:</label><input data-decoder="clng" type="text" name="clng" readonly /></p>





<ul id="log"></ul>


</section>

</div>


<script>
function initMap() {
  var mapLink = $("#mapLink");
  var log = $("#log");
  var watchID;

  $("#startWatchButton").click(function()
   {
    watchID = navigator.geolocation.watchPosition(showPosition, positionError);
   }
  );

  $("#clearWatchButton").click(function()
   {
    navigator.geolocation.clearWatch(watchID);
    logMsg("Stopped watching for location changes.");
   }
  );

  function showPosition(position) {

   logMsg("Showing current position.");

   var coords = position.coords;

   $("#clat").val(coords.latitude);
   $("#clng").val(coords.longitude);

   $("#cacc").val(coords.accuracy);
   $("#calt").val(coords.altitude);
   $("#caltAcc").val(coords.altitudeAccuracy);
   $("#cheading").val(coords.heading);
   $("#cspeed").val(coords.speed);
   $("#ctimestamp").val(coords.timestamp);

   var clat = latitude.dataset.decoder;
   var clng = longitude.dataset.decoder;

   clat.value = position.coords.latitude;
   clng.value = position.coords.longitude;

   mapLink.attr("href", "http://maps.google.com/maps?q=" + $("#clat").val() + ",+" + $("#clng").val() + "+(You+are+here!)&iwloc=A&hl=en");

   mapLink.show();
  }

  function positionError(e) {
   switch (e.code) {
    case 0:
     logMsg("The application has encountered an unknown error while trying to determine your current location. Details: " + e.message);
     break;
    case 1:
     logMsg("You chose not to allow this application access to your location.");
     break;
    case 2:
     logMsg("The application was unable to determine your location.");
     break;
    case 3:
     logMsg("The request to determine your location has timed out.");
     break;
   }
  }

  function logMsg(msg) {
   log.append("<li>" + msg + "</li>");
  }

  mapLink.hide();

}
</script>


</body>

</html>


I checked the code.I have this error “You chose not to allow this application access to your location” .The console did’t show me other errors.

It is a case number 1.
These are error messages.

Issue is that data set is not seen inside input even I try different Google maps.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.