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.
Related
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 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.
I need some help as I'm trying to call back a JavaScript function with PHP. I created 2 classes which work together perfectly. In the first one exploiting a Google API, I extract the latitude and longitude of a city chosen by a user on my form, and then I pass these values to the second class which exploits another API to show a weather forecast service for that city.
I'd like to add a Google map too, to create this way a more complete service showing a dynamic map with the chosen city.
I noticed with Firebug that the browser is not able to parse correctly the two mentioned properties of the object $map, as you can easily see by yourself.
I really don't know how to call back the js function inside the tag , I need for my purpose.
The simple echo I'm using here with PHP doesn't work here.
Hope someone can help me.
Here's my page
and here's the piece of my code that is not working:
/**
* Check for the real existence of the city, using the
* property $status of the instanced GeoLocalization class, here the object $map.
* This class exploits a Google API.
*/
if ( isset($missing) && empty($missing) && strlen($citta) > 1 && $map->status == 'OK' )
{
/**
* Use some properties of the object $map to show my user
* the chosen city and state in Italian.
* Show even the latitude and the longitudine.
* These values are those passed to the GeoWeather class.
*/
// show the location
echo '<ul id="display_location">' .
'<li class="rosso centra sottolineato grassetto">' . $map->formatted_address . '</li>' .
'<li>' . 'Latitudine: ' . $map->latitude . '</li>' .
'<li>' . 'Longitudine: ' . $map->longitude . '</li>' .
</ul>';
echo '<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>';
echo '<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(<?php echo $map->latitude . ", " . $map->longitude; ?>)
};
map = new google.maps.Map(document.getElementById("googleStaticMap"), mapOptions);
}
</script>';
echo '<script type="text/javascript">initialize();</script>';
echo '<div id="googleStaticMap"></div>';
}
</body>
You can't start a new PHP-block inside a PHP-block.
This:
echo '<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(<?php echo $map->latitude . ", " . $map->longitude; ?>)
};
map = new google.maps.Map(document.getElementById("googleStaticMap"), mapOptions);
}
</script>';
should be:
echo '<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng('. $map->latitude . ','
. $map->longitude .')
};
map = new google.maps.Map(document.getElementById("googleStaticMap"),
mapOptions);
}
</script>';
Other issues:
you must switch the order of these 2 lines(otherwise #googleStaticMap is unknown when you call the function):
echo '<script type="text/javascript">initialize();</script>';
echo '<div id="googleStaticMap"></div>';
Additionaly:
#googleStaticMap currently doesn't have a height. You've set a height of 100%, but as long as the parent element of #googleStaticMap doesn't have a height set via CSS this will not have any effect.
class Map
{
public $Id;
public $longitudes;
public $latitudes;
public $lat_init;
public $lng_init;
public static function createMap($Id){
global $latitude, $longitude;
$dbh = Database::connect();
$query = "SELECT * FROM `cartes` WHERE Id=? ";
$sth = $dbh->prepare($query);
$sth->setFetchMode(PDO::FETCH_CLASS, 'Map');
$sth->execute(array($Id));
if ($sth->rowCount() === 0) return NULL;
$map=$sth->fetch();
$sth->closeCursor();
$lat=$map->latitudes;
$lng=$map->longitudes;
$latitude=unserialize($lat);
var_dump($latitude);
$longitude=unserialize($lng);
echo'<script type="text/javascript">'
,'var lat = json_encode($latitude);
var lng = json_encode($longitude);
draw(lat,lng);
'
,'</script>';
}
}
<?php
$dbh=Database::connect();
Map::createMap(6);
?>
When i excute this code, the following error appears: "$latitude is not defined". var_dump($latitude) is ok. I think the script doesn't recognize $latitude but i don't know why. Any help?
thanks
If you're encoding it into JSON, you'll need to wrap it in quotes correctly (you can't call functions inside strings):
echo '<script type="text/javascript">
var lat = '. json_encode($latitude). ';
var lng = '. json_encode($longitude). ';
draw(lat,lng);
</script>';
With PHP, single quote are for string literals and will use the name of the variable instead of its value. If you want interpolation (inserting a variable's value into the string), you need to use double quotes.
echo '<script type="text/javascript">',
"var lat = ". json_encode($latitude) .";
var lng = ". json_encode($longitude) .";
draw(lat,lng);",
'</script>';
Update: I somehow overlooked the part about json_encode being a PHP call... so the interpolation issue is a moot point, since you just need to concatenate the function's output into the string.
Functions aren't called inside quoted strings. You need to concatenate it:
echo '<script type="text/javascript">
var lat = ' . json_encode($latitude) . ';
var lng = ' . json_encode($longitude) . ';
draw(lat,lng);
';
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
}