Pass a PHP array to Google Maps API JavaScript function - javascript

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,
......

Related

Javascript and PHP for each loop to output an array

I am trying to create a javascript array using content that is pulled from a php database.
<?php
//This creates an array from the database and allows us to use it later in the jquery
//CREATE SQL STATEMENT
$sql_locations = "SELECT * FROM tbllocations";
//CONNECT TO MYSQL SERVER
require('test-connection.php');
//EXECUTE SQL STATEMENT
$rs_locations = mysqli_query($vconnection, $sql_locations);
$rs_locations_rows = mysqli_fetch_assoc($rs_locations);
foreach( $rs_locations as $rs_location ) {
$markers[] = array(
"{$rs_location['place']}, {$rs_location['city']}",
$rs_location['long'],
$rs_location['lat']
);
}
?>
<div id="map_wrapper">
<div id="map_canvas" class="mapping"></div>
</div>
<style>
#map_wrapper {
height: 400px;
}
#map_canvas {
width: 100%;
height: 100vh;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: "roadmap",
center: new google.maps.LatLng(47.608941, -122.340145), // somewhere in the uk BEWARE center is required
zoom: 3,
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
// Multiple Markers
var markers = <?php echo json_encode( $markers ); ?>;
// Info Window Content
var infoWindowContent = [
<?php while($rs_location_rows = mysqli_fetch_assoc($rs_location)) { ?>
['<div class="info_content">' +
'<h3><?php echo $rs_locations_rows['branch']; ?></h3>' +
'<p><?php echo $rs_locations_rows['content']; ?></p>' +
'<p><?php echo $rs_locations_rows['phone']; ?></p>' +
'</div>']
<?php } ?>
];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow();
var marker, i;
// Loop through our array of markers & place each one on the map
for (i = 0; i < markers.length; i++) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
//Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function (event) {
this.setZoom(10);
google.maps.event.removeListener(boundsListener);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I have updated the code to show my whole page. I have tried this while loop in the meantime and adding that in stops my page from generating and outputting my map, so my page will hang.
I am thinking to do a for each loop the same way that I have done for the markers, but I have not succeeded thus far
As you are basically trying to build a string containing some js code and then pass it directly to the browser, I would build a string in PHP and then echo the lot in one go. Its easier to see what you are doing.
<?php
$js = '<script type="text/javascript">';
$js .= 'var infoWindowContent = [';
while( $row = mysqli_fetch_assoc($rs_location)) {
$js .= "['" . '<div class="info_content">';
$js .= "<h3>{$row['branch']}</h3>";
$js .= "<p>{$row['content']}</p>";
$js .= "<p>{$row['phone']}</p>";
$js .= "</div>'],";
}
// trim off the js interpreter breaking trailing comma
$js = rtrim( $js, ',' );
// close the outer array
$js .= '];';
$js .= '</script>';
echo $js;
?>
You just need to change the do while structure to while:
As also mentioned by #RiggsFolly. (sorry I see now)
var infoWindowContent = [
<?php while($rs_location_rows = mysqli_fetch_assoc($rs_location)) { ?>
['<div class="info_content">' +
'<h3><?php echo $rs_locations_rows['branch']; ?></h3>' +
'<p><?php echo $rs_locations_rows['content']; ?></p>' +
'<p><?php echo $rs_locations_rows['phone']; ?></p>' +
'</div>'],
<?php } ?>
];
This is the approach i would use to do that:
var myArray = [
<?php while ($rs_location_rows = mysqli_fetch_assoc($rs_location)) : ?>
{
'branch' : '<?= $rs_locations_rows["branch"] ?>',
'content' : '<?= $rs_locations_rows["content"] ?>',
'phone' : '<?= $rs_locations_rows["phone"] ?>'
},
<?php endwhile; ?>
];
console.log(myArray);
Now you have the array in your js.

How to extract coordinates from Google Maps link (PHP or Javascript)

I have a google map link that looks like this:
https://www.google.com/maps/place/Space+Needle/#47.620506,-122.349277,17z/data=!4m6!1m3!3m2!1s0x5490151f4ed5b7f9:0xdb2ba8689ed0920d!2sSpace+Needle!3m1!1s0x5490151f4ed5b7f9:0xdb2ba8689ed0920d
How can I extract coordinates from it in PHP or Javascript to get an array:
{47.620506, -122.349277}
If you're not using the api (Which isn't advisable), you could just put the page into a string, and extract the long/lat from within ... It's given multiple times on the page as the parameter ll ... I'm not very good with regex, so I'll give an example using strstr
<?php
$url='https://www.google.com/maps/place/Space+Needle/#47.620506,-122.349277,17z/data=!4m6!1m3!3m2!1s0x5490151f4ed5b7f9:0xdb2ba8689ed0920d!2sSpace+Needle!3m1!1s0x5490151f4ed5b7f9:0xdb2ba8689ed0920d';
$result=file_get_contents($url);
$ll=explode(',',substr(strstr(strstr($result,'?ll='),'&',true),4));
$long=$ll[0];
$lat=$ll[1];
?>
This is the code I am using on my web page at the moment. It is fairly easy to do as well.
<div id="map-canvas">
<script>
function initialize() {
var myLatlng;
var mapOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
//User Location
/* This is the cords */ myLatlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
//So if you want them individually just use position.coords.l...
//Please feel free to ask questions
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</div>
If you use php it is quite easy to query the maps api with just about any address that Google will recognize:
$address = 'Space+Needle';
$url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response);
$ltlg = array($result->results[0]->geometry->location->lat, $result->results[0]->geometry->location->lng);
Hope this helps
Try this:
public function getCoordinatesAttribute() {
$url = "https://www.google.com/maps/place/Space+Needle/#47.620506,-122.349277,17z/data=!4m6!1m3!3m2!1s0x5490151f4ed5b7f9:0xdb2ba8689ed0920d!2sSpace+Needle!3m1!1s0x5490151f4ed5b7f9:0xdb2ba8689ed0920d";
$url_coordinates_position = strpos($url, '#')+1;
$coordinates = [];
if ($url_coordinates_position != false) {
$coordinates_string = substr($url, $url_coordinates_position);
$coordinates_array = explode(',', $coordinates_string);
if (count($coordinates_array) >= 2) {
$longitude = $coordinates_array[0];
$latitude = $coordinates_array[1];
$coordinates = [
"longitude" => $longitude,
"latitude" => $latitude
];
}
return $coordinates;
}
return $coordinates;
}
In my case, I have to make sure that the link is a google map location URL as it all depends on
the character "#" in the url.

Trying to create multiple markers on Google Map from database lat longs

I have a database that gets latitude and longitude values inserted into it. I have created a PHP loop to pull these values out in an array and my hope is to create a marker for each point on a Google map. Here is the code that I need to adjust to do so:
<script type="text/javascript">
var mylat,mylong,request;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('map'), {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
mylat= <?php echo $postalLat; ?>;
mylong = <?php echo $postalLong; ?>;
request = {
origin: mylat+','+mylong,
destination: '<?php echo $latRefDef; ?><?php echo $this->item->gpslat; ?>,<?php echo $longRefDef; ?><?php echo $this->item->gpslong; ?>',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('panel'));
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
document.getElementById('loader').innerHTML = "";
}
});
//omitted database connection here to get array of values
$totalMarkers = count($results);
foreach($results as $result){
$gpsLats[] = $result->gpslat;
$gpsLongs[] = $result->gpslong;
}
$i = 0;
while ($i < $totalMarkers) {
$inc = $i++;
?>
var myLatlng = new google.maps.LatLng(<?php echo $gpsLats[$inc]; ?>,<?php echo $gpsLongs[$inc]; ?>);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
<?php
}
?>
</script>
My thought was that since the javascript which creates each marker is within the while loop then I would get one marker per entry. Unfortunately this is not functioning as I would like it to, any ideas on how to adjust it?
You are not attaching the map marker to the map itself, just creating the marker object. I usually use something like this:
$('#map_canvas').gmap('addMarker',{'position':new google.maps.LatLng(parseFloat(<?php echo $gpsLats[$inc]; ?>),parseFloat(<?php echo $gpsLongs[$inc]; ?>)});
This is how I define the marker.
var marker = new google.maps.Marker({
position: latLng,
title: "Test Marker",
visible: true,
map:myMap
});
And attach it to map
marker.setMap(myMap);
Just try if this helps. Just a thought, are the correct coordinates being output?
Not 100% sure why it wasn't working out with all that php code, but I whittled it down to this and it works now:
<?php
while ($i < $totalMarkers) {
$inc = $i++;
$myLats = $gpsLats[$inc];
$myLogns = $gpsLongs[$inc];
?>
var myLatlng = new google.maps.LatLng(<?php echo $myLats; ?>,<?php echo $myLogns; ?>);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
<?php
}
?>

Google Maps // "Uncaught TypeError: Cannot read property 'icon' of undefined"

I'm implementing Google Maps onto a Wordpress website that will allow the user to add locations to the Map using Advanced Custom Fields. The map loads in great, but the icons/markers don't seem to be loading in right. I get an error that reads, "Uncaught TypeError: Cannot read property 'icon' of undefined" in the Chrome Developer Tool Inspector.
Do I need to add anything? I'm new to Google Maps and firing it off and what not. Here's what I'm using:
<?php // Index template
get_header(); ?>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<div class="twelve column">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="intro">
<?php the_excerpt(); ?>
<hr>
</div>
<?php the_content(); ?>
<header class="clearfix"></header>
<div id="mapcanvas"></div>
<?php
// For creating multiple, customized loops.
// http://codex.wordpress.org/Class_Reference/WP_Query
$custom_query = new WP_Query('post_type=locations'); // exclude category 9
while($custom_query->have_posts()) : $custom_query->the_post(); ?>
<?php if(get_field('link')): ?>
<div>
<?php while(has_sub_field('link')): ?>
<div>
<p><?php the_sub_field('url'); ?></p>
</div>
<?php endwhile; ?>
</div>
<?php endif; ?>
<?php endwhile; ?>
<?php wp_reset_postdata(); // reset the query ?>
<?php
function get_single_term($post_id, $taxonomy)
{
$terms = wp_get_object_terms($post_id, $taxonomy);
if(!is_wp_error($terms)) {
return ''.$terms[0]->name.'';
}
}
$i = 0;
// For creating multiple, customized loops.
// http://codex.wordpress.org/Class_Reference/WP_Query
$custom_query = new WP_Query('post_type=location&posts_per_page=-1');
while($custom_query->have_posts()) : $custom_query->the_post();
$title = get_the_title(); // Location title
$map = get_field('location'); // ACF location contains address and coordinates
$terms = strip_tags( get_the_term_list( $post->ID, 'distributors', '', ' & ' )); // Get distributor terms and rm links
$info = '<strong>' . $terms . '</strong><br>' . $title; // Info window content
$url = the_sub_field('url');
if(get_field('link')){
echo '<ul>';
while(has_sub_field('link')){
$info .= '<li>'.get_sub_field('url').'</li>';
}
echo '</ul>';
}
$location[$i][0] = $title; // Store the post title
$location[$i][1] = $map['coordinates']; // Store the ACF coordinates
$location[$i][2] = json_encode($info); // Store info window content
$location[$i][3] = strip_tags( get_single_term( $post->ID, 'distributor' )); // Get first term for marker icon
$i ++;
endwhile; ?>
<?php wp_reset_postdata(); // reset the query ?>
<script>
$(function initialize() {
// Center map on our main location
var myLatLng = new google.maps.LatLng(41.583013,-93.63701500000002);
var map;
var bounds = new google.maps.LatLngBounds();
// https://developers.google.com/maps/documentation/javascript/styling
// Create an array of styles.
var styles = [
{
stylers: [
{ saturation: -99.9 }
]
}
];
// Create a new StyledMapType object, passing it the array of styles,
// as well as the name to be displayed on the map type control.
var styledMap = new google.maps.StyledMapType(styles, {name: 'exile'});
// Create a map object, and include the MapTypeId to add
// to the map type control.
var mapOptions = {
mapTypeId: 'roadmap',
center: myLatLng,
zoom: 8,
disableDefaultUI: false,
scrollwheel: true,
draggable: true
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("mapcanvas"), mapOptions);
map.setTilt(45);
//Associate the styled map with the MapTypeId and set it to display.
map.mapTypes.set('exile', styledMap);
map.setMapTypeId('exile');
// Marker icons
typeObject = {
"Home" : {
"icon" : new google.maps.MarkerImage('img/target.png', new google.maps.Size(28,28), new google.maps.Point(0,0), new google.maps.Point(36,14)),
"shadow" : new google.maps.MarkerImage('http://maps.google.com/mapfiles/shadow50.png', new google.maps.Size(40,34))
},
"Others" : {
"icon" : new google.maps.MarkerImage('img/beer-mug.png', new google.maps.Size(18,26), new google.maps.Point(0,0), new google.maps.Point(9,26)),
"shadow" : new google.maps.MarkerImage('http://maps.google.com/mapfiles/shadow50.png', new google.maps.Size(40,34))
}
}
// http://wrightshq.com/playground/placing-multiple-markers-on-a-google-map-using-api-3/
// Multiple Markers
var markers = [
["Exile Brewing Co", 41.583013,-93.63701500000002,"Others"],
<?php
if (count($location)>0) {
foreach ($location as $key => $value){
if ($key < (count($location)-1)){
echo '["' . $location[$key][0] . '",' . $location[$key][1] . ',"' . $location[$key][3] . '"], ' . "\n";
} else {
echo '["' . $location[$key][0] . '",' . $location[$key][1] . ',"' . $location[$key][3] . '"]';
}
}
}
?>
];
// Info Window Content
var infoWindowContent = [
["<strong>Exile Brewing Co.</strong><br>1514 Walnut Street, Des Moines"],
<?php
if (count($location)>0) {
foreach ($location as $key => $value){
if ($key < (count($location)-1)) {
echo '[' . $location[$key][2] . '], ' . "\n";
} else {
echo '[' . $location[$key][2] . ']';
}
}
}
?>
];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]); // ACF coordinates
var icon = typeObject[markers[i][3]]['icon'];
var shadow = typeObject[markers[i][3]]['shadow'];
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0],
icon: icon,
shadow: shadow
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
//map.fitBounds(bounds);
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(15);
google.maps.event.removeListener(boundsListener);
});
});
</script>
<div id="panel">
Search within
<input id="address" type="textbox" value="10">
miles of zipcode
<input id="address" type="textbox" value="50266">
<input class = "button" type="button" value="Find it!" onclick="codeAddress()">
</div>
<footer class="clearfix"></footer>
<?php endwhile;?>
<?php endif; ?>
</div>
</div>
<?php get_footer(); ?>
Here's the link to the page I'm working on too:
http://exilebrewing.com/locations/
Any help is appreciated, thanks!
The typeObject contains 2 properties (Home and Others)
Your script will fail when the 4th item of a item in markers doesn't match 1 of these property-names.
This currently happens:
var markers = [
["Exile Brewing Co", 41.583013,-93.63701500000002,"Others"],
["Exile Brewing Co",41.583013,-93.63701500000002,""]
//this must be either Home or Others--------------^
];
You may either fix markers or use a fallback when the property can't be found:
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
//use typeObject.Others when property can't be found
var icon = (typeObject[markers[i][3]]||typeObject.Others).icon;
var shadow = (typeObject[markers[i][3]]||typeObject.Others).shadow;
//continue with your code
}

how to add google Directions in google maps

The current code retrieves all info, displays all markers on a map and if a marker is clicked, infowindow renders showing its content. What i want to do is that i want to implement directions in this. How can i add directions in my code so that it will also add directions? This is what i want to implement:
what to implement :
var request = {
origin: start,//it will be my first row(lat and lon)
destination: end,//it will be my lastrow(lat and lon)
waypoints: waypts, // it will be all lat and lon between first and last
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status){
if (status == google.maps.DirectionsStatus.OK){
directionsDisplay.setDirections(response);
}
});
My current code in which i want to implement the above functionality mean google maps directions:
already implemented :
$("#directions").click(function(){
var lat_from_ip = $("#hidden_lat").val();
var lon_from_ip = $("#hidden_lon").val();
var latlng = new google.maps.LatLng(lat_from_ip, lon_from_ip);
var options = {zoom: 4, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById('map'), options);
$.ajax({type: "GET",
dataType: 'json',
url: url +'//abc/my_page.php',
success: function(response){
var total=response.length;
var data_array,name,type,address,lat,lon,infowindow;
var infowindow = new google.maps.InfoWindow();
for(var i=0; i < total; i++)
{
data_array=response[i];
name=data_array['name'];
address=data_array['address'];
notes=data_array['notes'];
lat=data_array['lat'];
lon=data_array['lon'];
var propPos = new google.maps.LatLng(lat,lon);
propMarker = new google.maps.Marker({
position: propPos,
map: map,
icon: icon,
zIndex: 3});
var contentString = "<div>"+name+"<br/><label class='label'>Location :</label> "+address+"<br/><label class='label'>Notes :</label> "+notes + "</div>";
function bindInfoWindow(marker, map, infowindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(html);
infowindow.open(map, marker);
});
}
bindInfoWindow(propMarker, map, infowindow, contentString);
} //end of for loop
} //end of for success
}); //end of for $.ajax
return;
});
Function to draw directions, call it whenever you want to show directions. You can pass some variables to it, and use them inside, to decide which markers will be start, end and waypts.
function calcRoute() {
var startpt = yourstartlatlng;
var endpt = yourendlatlng;
var waypts = [] //your waypts array, if there are more than 1 point
var request = {
origin:startpt,
destination:endpt,
waypoints: waypts,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
Example from here: Google Maps Api
EDIT:
When you have an array in php called waypts, and you want to have these values in javascript, you need to pass them to java. Its kinda messy, but thats the only way i know:
<script type="text/javascript">
var waypts = [];
<?php
$waypts= array(1, 2, 3, 4); //<-- your array, can be called like that, or just have values inside already
for($i = 0; $i < sizeof($waypts); $i++){
?>
waypts[<?php echo $i; ?>] = <?php echo $waypts[$i]; ?>; //php is interpreted before java, when site will load, these values will be inside java "waypts" variable.
<?php
}
?>
alert(""+waypts[1]);
</script>
That code will put your php variables/array into java array (alert is just to check if it did the job, you can delete it, once you understand the code). Then you can use these variables however you want. PHP is interpreted earlier than java, so in site code you will get waypts[0] = 1; cuz php code will be already replaced by values from array.
This is how to convert your php array to js array
for instance you have php array
<?php
$my_array = array("a","b","c");
?>
now in js do so
<script>
var jsArray = ["<?php echo join("\", \"", $my_array); ?>"];
alert(jsArray);
and in your domain its like this.
lets say you have php array like this.
$data ;//this is your php array
Array
(
[0] => Array
(
[lat] => 31.453795
[lon] => 74.388497
)
[1] => Array
(
[lat] => 31.454387
[lon] => 74.388541
)
[2] => Array
(
[lat] => 31.453795
[lon] => 74.388497
)
.
.
.
)
in js do so
var waypts = [];
<?php
foreach($data as $key => $value){
if(($key == '0') || ($key == count($data)-1)){
continue;
}?>
waypts.push({location: new google.maps.LatLng(<?php echo $data[$key]['lat'] ?>, <?php echo $data[$key]['lon'] ?>)});
<?php }?>

Categories