Can't input array from php to javascript - javascript

I have this code:
<?php $result = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$result[] = sprintf("{lat: %s, lng: %s}",$row['lat'],$row['lng']);} ?>
<?php $resultAM = join(', ',$result);
echo $resultAM; ?>
the $resultAM represents this result (anyway I'm using SQL):
{lat: -7.0476101, lng: 112.7323577}, {lat: -7.0319093, lng: 112.7614287}, {lat: -7.0433001, lng: 112.7606889}, {lat: -7.0459718, lng: 112.7583679}
I'm going to put the code in javascript with this code:
var distanceM = [<?php echo json_encode($resultAM); ?>];
but the result wont appear.
Anyone can help me? I'm new at PHP. Thanks!

PHP 2D Array can simply transform into JS Array of objects. For example, we have a php array:
$arr = array('city1' => array('TBILISI' => 'Georgia'), 'city2' => array('LONDON' => 'UK'));
In JS we can simply write:
let myArr = <?php echo json_encode($arr); ?>;
console.log(myArr); // Console it..
it now looks in JS like that:
{"city1":
{"TBILISI": "Georgia"},
"city2":
{"LONDON": "UK"}
}

Related

how to create google maps marker with custom field values?

I just placed a google map on my website following the instructions from google maps API: https://developers.google.com/maps/documentation/javascript/adding-a-google-map
Copying that example works perfectly but I would like to get the position of the marker depending on a custom field created in each post from WordPress
<div id="map"></div>
<?php $lati = get_field( "gmapslat" ); ?>
<?php $lat = get_field( "gmapslng" ); ?>
<script>
function initMap() {
var lat = '<?php echo $lat; ?>';
var lng = '<?php echo $lng; ?>';
var uluru = {lat: lat, lng: lng};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
<script async defer
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDPGx6I2w6hzEmQNR2IrRKlFC9oUT-COvs&callback=initMap">
</script>
</div>
When do that the map just shows grey.
It seems there's a problem with your PHP variables. This PHP Variable $lng is not declared. So you are setting an undeclared PHP variable in Javascript variable lng.
I also noticed these lines:
<?php $lati = get_field( "gmapslat" ); ?>
<?php $lat = get_field( "gmapslng" ); ?>
Is this variable $lat value a longitude? If so, use $lng instead. Using meaningful names for variables would be helpful. Variable names must define the exact explanation of its content, regardless of programming language. Checking this blog 15 Best Practices of Variable & Method Naming might help.
Important: Use parseFloat() on each javascript variable width coordinates to return a floating point number. Else, it won't work and you'll just see a grey map. To learn more about definition and usage of parseFloat(), you can check JavaScript parseFloat() Function.
Below is a sample code using "-25.363, 131.044" as a sample coordinates returned by your PHP get_field() function:
<div id="map"></div>
<?php
function get_field($args) {
switch ($args) {
case 'gmapslat':
return '-25.363';
break;
case 'gmapslng':
return '131.044';
break;
}
}
$lat = get_field('gmapslat');
$lng = get_field('gmapslng');
?>
<script>
function initMap() {
var lat = parseFloat("<?php echo $lat; ?>");
var lng = parseFloat("<?php echo $lng; ?>");
var myLatLng = {lat: lat , lng: lng};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
Hope it could help and happy coding!

I can't make a google maps marker

I have got my Coordinates from my Database, the problem is that, I can not add a marker with data.
If I put the coordinates manually then it works fine without any problems, but if I get the coordinates value from my Database, google maps, it doesn't work.
This is my code:
function myFunction() {
var latitud = <?php echo '["' . implode('", "', $dbLatitud) . '"]' ?>;
var longitud = <?php echo '["' . implode('", "', $dbLongitud) . '"]' ?>;
document.getElementById("demo").innerHTML = latitud + longitud;
// document.getElementById("demo").innerHTML = fruits[1]; --- especifico slot
var a = latitud.toString();
var b = longitud.toString();
var myLatLong = {lat: a, lng: b};
var marker = new google.maps.Marker({
position: myLatLong,
map: map,
title: 'Colectivo N°: 1'
});
marker.setMap(map);
}
I think the problem is with data types. Type of the database coordinates are in double, but I can't make a marker with other type data neither.
I could solve it!
I changed .toString()
function myFunction() {
var latitud = <?php echo '["' . implode('", "', $dbLatitud) . '"]' ?>;
var longitud = <?php echo '["' . implode('", "', $dbLongitud) . '"]' ?>;
var a = latitud.toString();
var b = longitud.toString();
var myLatLong = {lat: a, lng: b};
}
with parseFloat();
function myFunction() {
var latitud = <?php echo '["' . implode('", "', $dbLatitud) . '"]' ?>;
var longitud = <?php echo '["' . implode('", "', $dbLongitud) . '"]' ?>;
var a = parseFloat(latitud);
var b = parseFloat(longitud);
var myLatLong = {lat: a, lng: b};
}
More simply don't cast the values as strings to begin with -- in other words remove the double quotes.
You can use <?= and ?> as short hand to echo php variable without writing echo.
I haven't tested my assertion, but the documentation seems to suggest that you can't simply implode multiple values into myLatLong. Do you actually only have one value for lat and long? If so, this will do:
var marker = new google.maps.Marker({
position: {lat:<?=$dbLatitud[0]);?>, lng:<?=$dbLongitud[0];?>},
map: map,
title: 'Colectivo N°: 1'
});
Furthermore, you could prep your data for direct insertion into the javascript using an associated array and json_encode():
<?php
$lats=['lat'=>-33.890542];
$lng=['lng'=>151.274856];
?>
...
position: <?=json_encode($lats+$lng);?>
If you do have multiple markers, then see this demo which uses a multidimensional array of data and uses a loop to apply all of the markers. In which case, you again can/should use json_encode() in your php to prepare/format your database values for javascript.

loading a map by lat and lang stored in a database

I have google map embedded in a page with a Dropdown list containing a number of cities. I have stored the lat and lang values of those cities in a database. A user will select a city and the map will load with respective lat and lang values upon clicking the submit button. Please note that I don't want the geocoding technique. Here is a snippet of my effort.
var map;
var cntr;
var zm;
<?php
if(!empty($position['lat']) && !empty($position['lang'])){ ?>
var latValue = <?php $position['lat']; ?> ;
var langValue = <?php $position['lang']; ?> ;
cntr = {lat: latValue , lng: langValue };
zm = 8;
<?php} else{ ?>
cntr = {lat: 30, lng: 70};
zm = 7;
<?php } ?>
function initialize() {
var mapOptions = {
center: cntr,
zoom: zm
};
//And the rest of the code for markers and infowindows etc.
This doesn't work. It even stops the rest of the code to work which perfectly works when I remove this section and assign the default values to the var cntr.
(I am using MVC organization and the $position is an associative arrray of the cities lat and lang in the controller. The query works perfectly.)
You can't use php inside a .js file by default.You have to change your .htaccess accordingly.
Here is a site from a fast google search on how to do it. https://css-tricks.com/snippets/htaccess/use-php-inside-javascript/
cntr = {lat: latValue , lang: langValue };
That should say lng not lang.
I'm not sure how that would have been reported in the console; it would probably throw an error deep in the API code.
if(!empty($position['lat'] && !empty($position['lang'])))
shouldn't this be:
if(!empty($position['lat']) && !empty($position['lang']))
?
You have two errors in the code you have provided. First, you have to say
<?php echo $position['lat']; ?>
not
<?php $position['lat']; ?>
Second, instead of taking the default values for lat and lng inside the php loop, initialize the variables at the time you declare them. So the code you need will look something like:
var map;
var cntr = {lat: 30, lng: 70};
var zm = 7;
<?php if(!empty($position['lat']) && !empty($position['lang'])){ ?>
var latValue = <?php echo $position['lat']; ?> ;
var langValue = <?php echo $position['lang']; ?> ;
cntr = {lat: latValue, lng: langValue};
zm = 8;
<?php } ?>
function initialize() {
var mapOptions = {
center: cntr,
zoom: zm
};
//rest of the code
Hope this helps you.

Generate Markers from Mysql Database

I have an array of markers coded into a web page and I use them to generate markers for a google map in the form of
generateMarkers([['Location', lat, long], ['Location2', lat2, long2],['Location3', lat3, long]3]);
So now am attempting to retrieve marker positions from a database so I attempted to use the code below to do so
getmkrs(
<?php
$db_con = mysql_connect("localhost",'root','');
mysql_select_db("db_name",$db_con);
$query_db = "Select * From table_name";
$result = mysql_query($query_db, $db_con);
$joiner = '';
?>
var_markers = [<?php while($row = mysql_fetch_assoc($result)):?>
<?= $joiner ?>
[<?= $addslashes($row['Row1']) ?>, <?= $row['Row2'] ?>, <?= $row['Row3'] ?> ]
<?$joiner = ','?>
<?php endwhile; ?>];
);
But Ultimately the page turns up blank, not even the map shows up. I am trying to replicate the above array which I coded into the web page. So my question is how can I efficient generate markers using data from a databse
For the love of god, don't cobble together JSON by hand interspersed in Javascript code. Create a sane data structure in PHP and encode it using json_encode:
<?php
$db_con = mysql_connect("localhost", 'root', '');
mysql_select_db("db_name", $db_con);
$query_db = "SELECT * FROM table_name";
$result = mysql_query($query_db, $db_con);
$markers = array();
while ($row = mysql_fetch_assoc($result)) {
$markers[] = array($row['Row1'], $row['Row2'], $row['Row3']);
}
?>
<script>
var markers = <?php echo json_encode($markers); ?>;
generateMarkers(markers);
</script>

Pass a PHP array to Google Maps API JavaScript function

I am trying to create a way to loop through a bunch of address and output a list of ones that are within a set distance from another address. So In WordPress, I have a custom post type I am looping through and creating an array of addresses like this,
<?php
$args = array( 'post_type' => 'friday_location', 'posts_per_page' => '-1' );
$arr = array();
$i=0;
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$meta = get_post_meta( $post->ID);
$string = $meta['_cmb_address'][0] . '+' . $meta['_cmb_city'][0] . '+' .$meta['_cmb_state'][0] . '+' .$meta['_cmb_zip'][0];
$string = str_replace(' ', '+', $string);
$arr[$i] = $string;
$i++;
endwhile;
wp_reset_postdata();
?>
After this, inside of the script tag I am converting the array like this
var locations = <?php echo json_encode($arr ); ?>;
Now I have a JS array, I think, of addresses and I am wanting to pass this array into the Google Maps API Distance Matrix, https://developers.google.com/maps/documentation/javascript/distancematrix#distance_matrix_requests
The relevant code piece looks like,
function calculateDistances() {
var opts = {
center: new google.maps.LatLng(38.6,-98),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), opts);
geocoder = new google.maps.Geocoder();
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin2],
destinations: locations,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, callback);
}
I know the destinations can take an array, so I am trying to give it one, dynamically made, however I am not sure why it is not working as I see it in my head :)
This:
var locations = <?php echo json_encode($arr ); ?>;
should probably be:
var locations = '<?php echo json_encode($arr ); ?>';
But that's just a string, to get an array do:
var locations = '<?php echo json_encode($arr ); ?>',
JSON = JSON.parse(locations),
loc_array = [];
for(var key in JSON) {
if(JSON.hasOwnProperty(key)) {
loc_array.push(JSON[key]);
}
}
now pass that array to the Google function:
service.getDistanceMatrix(
{
origins: loc_array,
......

Categories