Passing data from JS to PHP is not working - php

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;
?>

Related

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

Passing value correctly to PHP from AJAX Code

So I'm trying to pass a value from my AJAX code to my PHP code which connects to an API to get the weather. It works when just using PHP, but I want ajax to return the results to some div on the same page. My code looks correct when I compare it to other examples but it just doesn't work.
Code may not be written with security in mind, standard practice etc, I'm just trying to play around with API's and get the basics of AJAX.
api.php:
$city = $_POST['city'];
function getCityLat($x) {
$latUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='. $x .'APIKEY';
$latResponse = file_get_contents($latUrl);
$latArray = json_decode($latResponse, true);
$lat = $latArray['results'][0]['geometry']['location']['lat'];
echo $lat;
return $lat;
}
function getCityLng($y) {
$lngUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='. $y .'APIKEY';
$lngResponse = file_get_contents($lngUrl);
$lngArray = json_decode($lngResponse, true);
$lng = $lngArray['results'][0]['geometry']['location']['lng'];
echo $lng;
return $lng;
}
function getWeather($x, $y) {
$weatherUrl = 'https://api.darksky.net/forecast/APIKEY/' . $x . ',' . $y;
$weatherResponse = file_get_contents($weatherUrl);
$weatherArray = json_decode($weatherResponse, true);
$timeZone = $weatherArray['timezone'];
$locWeather = $weatherArray['currently']['temperature'];
$locFeelsLike = $weatherArray['currently']['apparentTemperature'];
$windSpeed = $weatherArray['currently']['windSpeed'];
$weatherSummary = $weatherArray['currently']['summary'];
$time = $weatherArray['currently']['time'];
$outputweather = '<p>Temp: '.$locWeather.'</p>';
echo $outputweather;
}
getWeather(getCityLat($city), getCityLng($city));
?>
index.php(html):
<h3 align="center">Weather</h3>
<form align="center" method="POST">
<input type="text" id="city" name="city" placeholder="Enter City">
<button class="btn btn-xs btn-success" name="city_go" id="city_go">Go</button>
</form>
<div id="weather"></div>
JQuery:
function getWeather(city) {
$.ajax({
url: "api.php",
method: "POST",
data: {city:city},
dataType: "text",
success: function(data) {
$('#weather').html(data);
}
});
}
$(document).on('click', '#city_go', function() {
var city = $('#city').val();
getWeather(city);
});
The problem is that you are submitting a form, which forces a page refresh. Everything else is working correctly, just the page is being refreshed. To fix that you need to update your click event to something like
$(document).on('click', '#city_go', function(e) {
e.preventDefault();
var city = $('#city').val();
getWeather(city);
});
the preventDefault() call will cancel the default action of the form (the page refresh) and allow the AJAX call to follow through and display the data.

How to render a route on google map with lat long from previous page by html form?

I want to render route on google map by lat long from previous page(send by html form)
and put the recieve value on php hidden type then pull value by jquery and define a start,end point
from value in hidden type finally call routefunction but it's not show the way route
I try to put alert in render section it's work fine but not show way route.I don't know why
This is my code
<?php
//get lat long from previous page html form
$press = $_POST["send"];
$lat1 = $_POST["lat1"];
$long1 = $_POST["long1"];
$lat2 = $_POST["lat2"];
$long2 = $_POST["long2"];
?>
<!DOCTYPE html>
<head>
<script type="text/javascript" src="./jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=my_key&sensor=false"></script>
<script type="text/javascript">
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var rendererOptions = {draggable: true}; //define dragble direction
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var center = new google.maps.LatLng(13.76493,100.5383);
var mapOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: center
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); //render map
calcRoute(); //call route function
}
function calcRoute()
{//get lat long from hidden type
$(document).ready(function(){
var lat1 = $("#lat1").val();
var long1 = $("#long1").val();
var lat2 = $("#lat2").val();
var long2 = $("#long2").val();
var start = new google.maps.LatLng(lat1,long1);//define start point
var end = new google.maps.LatLng(lat2,long2);//define end point
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
alert("DO"); //it's show alert when redirect from previous page
}
});
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:500px; height:400px"></div>
<?php
//put value from previous page on hidden type
echo "<input type='hidden' id='lat1' value='$lat1'>";
echo "<input type='hidden' id='long1' value='$long1'>";
echo "<input type='hidden' id='lat2' value='$lat2'>";
echo "<input type='hidden' id='long2' value='$long2'>";
?>

set polylines in googlemap from values in PHP

I have seen this link:
Google map api v3 add polylines from array
this is somehow slightly the same as my problem.. you see, im getting a javscript error as such this:
Uncaught TypeError: Cannot call method 'getPath' of undefined
AddCoordinate map:118
(anonymous function)
well my code is basically populating the coordinates first as the page is loaded together with the map.. And by the time that click is triggered (html button), that is the only time that the map will be plotted with poly lines.. I hope I explained it very well though.. Here's what i got:
var map;
var Markers = [];
var Coordinates = [];
var LinePath;
function initialize()
{
var myLatLng = new google.maps.LatLng(21.291982, -140.821856);
var myOptions = {
zoom: 3,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var MarkerSize = new google.maps.Size(48,48);
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function AddCoordinate( lat, long ) {
var path = LinePath.getPath();
path.push( new google.maps.LatLng( lat, long ) );
LinePath.setPath(path);
}
function PlotLine()
{
LinePath = new google.maps.Polyline({
path:Coordinates,
strokeColor:"#ffffff",
strokeOpacity:1.0,
strokeWeight:5
});
LinePath.setMap(map);
}
<html>
<body onload="initialize()">
<div id="map_canvas" ></div>
<?php
foreach($arrayOfPlotPoints as $key => $value){
$longitude = round($value['longitude'],5);
$latitude = round($value['latitude'],5);
$snrLevel = $value['snr_level'];
echo '<script type="text/javascript">AddCoordinate('.$latitude.','.$longitude.')</script>';
?>
<option value="<?php echo $longitude.",".$latitude.",".$snrLevel?>"> Lg:<?php echo $longitude." Lt: ".$latitude." LV: ".$snrLevel?></option>
<?php } ?>
</select>
<br /><br />
<?php echo $this->Form->button('PLOT', array('type'=>'button', 'onclick'=>'PlotLine()')); ?>
echo $this->Form->button('PLOT', array('type'=>'button', 'onclick'=>'PlotLine()'));
?>
********EDITED**********
i have made a partial modification of my code.. however im getting the same error..
Uncaught TypeError: Cannot call method 'getPath' of undefined
AddCoordinate (anonymous function)
function initialize() {
//.....
LinePath = new google.maps.Polyline({
path:Coordinates, //san ka galing Coordinates??? dineclare ka pero di ka aman nilagyan "YATA" ng laman
strokeColor:"#ffffff",
strokeOpacity:1.0,
strokeWeight:5
});
}
function AddCoordinate( latitude, longitude ) {
var path = LinePath.getPath();
path.push( latitude, longitude );
}
function PlotLine()
{
LinePath = new google.maps.Polyline({
path:Coordinates,
strokeColor:"#ffffff",
strokeOpacity:1.0,
strokeWeight:5
});
LinePath.setMap(map);
}
<HTML>
select name="long_and_lat" id="long_and_lat" style="width:220px;height:250px;" size="100">
<?php
$plotPoints = array();
foreach($arrayOfPlotPoints as $key => $value){
$longitude = round($value['longitude'],5);
$latitude = round($value['latitude'],5);
$snrLevel = $value['snr_level'];
echo '<script type="text/javascript">AddCoordinate('.$latitude.','.$longitude.')</script>';
?>
<option value="<?php echo $longitude.",".$latitude.",".$snrLevel?>"> Lg:<?php echo $longitude." Lt: ".$latitude." LV: ".$snrLevel?></option>
<?php } ?>
</select>
<br /><br />
<?php echo $this->Form->button('PLOT', array('type'=>'button', 'onclick'=>'PlotLine()')); ?>
</html>
You are making a call to LinePath in AddCoordinate(), but LinePath isn't created until PlotLine() is called (by clicking the button).
Perhaps you could create LinePath when you declare it, then just call LinePath.setMap(map); from PlotLine().
Maybe something like this:
<html>
<head>
<link href="https://google-developers.appspot.com/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var Markers = [];
var Coordinates = [];
var LinePath = new google.maps.Polyline({
path:Coordinates,
strokeColor:"#ffffff",
strokeOpacity:1.0,
strokeWeight:5
});
function initialize()
{
var myLatLng = new google.maps.LatLng(21.291982, -140.821856);
var myOptions = {
zoom: 3,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var MarkerSize = new google.maps.Size(48,48);
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function AddCoordinate( lat, long ) {
var path = LinePath.getPath();
path.push( new google.maps.LatLng( lat, long ) );
LinePath.setPath(path);
}
function PlotLine()
{
LinePath.setMap(map);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" ></div>
<script type="text/javascript">AddCoordinate(11,12)</script>
</body>
</html>

Google maps showing a visitor’s location by grabbing their IP address

I'm trying to replicate the following exemple :
http://www.leigeber.com/2008/04/map-your-users-using-the-google-maps-api-and-php/
How to integrate this PHP source code with the following Java script (replacing lat/lgt with $latitude/$longitude above ??? Looks easy but I'm a bit lost in mixing PHP and Javascript together ! ;-(
<script type="text/javascript">
function initialize() {
var map;
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
var zoomlevel = 9;
var lat= 50.62829913465776;
var lgt= 4.650295972824097;
map.setCenter(new GLatLng(lat, lgt), zoomlevel);
// add a marker
map.openInfoWindow(map.getCenter(), document.createTextNode ("Center of the map at (lat - lgt)= ("+lat+" - "+lgt+") ! "));
// Large Map Default UI
map.setUIToDefault();
// Map type
map.setMapType(G_PHYSICAL_MAP);
}
}
</script>
<body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 1000px; height: 600px"></div>
</body>
Thanks in advance for your help.
Hub
ps: is this the best way to do it ? is it good to use hostip.info or should I use another one ??
Should be fairly easy. Once you've fetched the $latitude and $longitude according to the linked example, you can use PHP to echo those values out to your Javascript code.
<script type="text/javascript">
function initialize() {
var map;
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
var zoomlevel = 9;
var lat= <?php echo $latitude ?>;
var lgt= <?php echo $longitude ?>;
map.setCenter(new GLatLng(lat, lgt), zoomlevel);
.........
...............
</script>
That should get you going for the script mixing part. Remember, you've to use PHP to fetch the lat/long BEFORE you attempt to output the values to your JS.
In response to your queries, here's the general flow of code (say, in the file index.php):
<?php
// Code from the blog
$ip = $_SERVER['REMOTE_ADDR'];
.....
.......
$latitude = $res[2];
$longitude = $res[3];
?>
<html>
<head>
<script type="text/javascript">
function initialize() {
var map;
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
var zoomlevel = 9;
var lat= <?php echo $latitude ?>;
var lgt= <?php echo $longitude ?>;
map.setCenter(new GLatLng(lat, lgt), zoomlevel);
.........
...............
}
</script>
</head>
<body onload="initialize()" onunload="GUnload()">
......
</body>
</html>
See if this helps you :)
Cheers,
m^e
According to this post http://www.techsirius.com/2014/07/visitor-realtime-geo-location-in-google-map.html it seems it is possible.
Basically it is fetching database record for country, state, and city based on given IP. It seems that database IP record is stored in IPlong format that is why it is possible to store that much IP record in one database.
After that all depended on Google Geocoding API and Google Maps JS v3 API.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true&key=<?=$google_api_key?>"></script>
<script type="text/javascript">
$(document).ready(function(){
var option = {
center: new google.maps.LatLng(<?=$lat?>, <?=$lng?>),
zoom: 5
};
var map = new google.maps.Map(document.getElementById("visitor_map"), option);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(<?=$lat?>, <?=$lng?>),
map: map
});
});
</script>

Categories