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!
Related
i have try to fetch lat and long value from mysql db and pass those value on google map for show location marker on map
but currently i have fetch only last rows data so indicate marker only one place
how to display all location on map??
<?php
include "config.php";
$result="select * from ds_duty_history";
$a=mysqli_query($conn,$result);
// $count_row = mysqli_num_rows($a);
while ($b = mysqli_fetch_array($a)) {
$long_d=$b['lng'];
$lat_d=$b['lat'];
$result = array(array('latitude'=>$lat_d,'longitude'=>$long_d));
}
?>
<!doctype html>
<html>
<head>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOURKEY&callback=initMap">
</script>
<script type="text/javascript">
var map;
function initialize() {
// Set static latitude, longitude value
var latlng = new google.maps.LatLng(<?php echo $lat_d; ?>, <?php echo $long_d; ?>);
// Set map options
var myOptions = {
zoom: 16,
center: latlng,
panControl: true,
zoomControl: true,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// Create map object with options
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?php
// uncomment the 2 lines below to get real data from the db
// $result = mysql_query("SELECT * FROM parkings");
// while ($row = mysql_fetch_array($result))
foreach($result as $row){ // <- remove this line
echo "addMarker(new google.maps.LatLng(".$row['latitude'].", ".$row['longitude']."), map);";}
?>
}
function addMarker(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map,
draggable: true, // enables drag & drop
animation: google.maps.Animation.DROP
});
return marker;
}
</script>
</head>
<body onload="initialize()">
<div style="float:left; position:relative; width:550px; border:0px #000 solid;">
<div id="map_canvas" style="width:550px;height:400px;border:solid black 1px;"></div>
</div>
</body>
</html>
currently display only one marker i.e last fetch record lat and long assign on map
how to display all place on map using mysql lat,long value?
The main problem you have here is that you're not actually collecting different results in your $result variable but overwrite it with the most recent one. The also seems to be some abuse of the variable $result which might be contributing to your confusion. Let's say we declare a new array and call it $rows. Then we can collect all the rows with the following code (to substitute your first snippet):
<?php
include "config.php";
$sql = "SELECT * FROM ds_duty_history";
$result = mysqli_query($conn, $sql);
$rows = [];
while ($row = mysqli_fetch_array($result)) {
$lon_d = $row['lng'];
$lat_d = $row['lat'];
// Use short-cut append syntax here so we add row and don't overwrite $rows
$rows[] = ['latitude' => $lat_d, 'longitude' => $long_d];
}
?>
Now in your display code (the second snippet) you would be able to iterate over $rows pretty much like:
foreach ($rows as $row){
// Do work with each $row here
}
Just as an aside, try to get used to using variable names that are as meaningful as possible and use new variables as much as you can. Trying to use short, generic variable names like $a will always lead to confusion since you won't know what it represents unless you find where you declared it every time. Trying to re-use a variable (like you did with $result) can make your life much more difficult since now even if you find an assignment to the variable, it is assigned many different times and (the way you used it) represents completely different types each time. Doing this one thing makes it just a little easier to get the hang of programming since at the very least you'll be able to read and make sense of your own intent when reading your own code.
Please try this code for display multiple marker on map
<script type="text/javascript">
var LocationData = <?php echo json_encode($result); ?>;
function initialize()
{
var myOptions = {zoom:12,mapTypeId: google.maps.MapTypeId.ROAD};
var map =
new google.maps.Map(document.getElementById('map-canvas'), myOptions);
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
for (var i in LocationData)
{
var p = LocationData[i];
var latlng = new google.maps.LatLng(p[0], p[1]);
bounds.extend(latlng);
var icon = { url: '<?php echo base_url();?>assets/frontend/assets/images/location_pin1.png', // url
scaledSize: new google.maps.Size(40, 70), // scaled size
origin: new google.maps.Point(0,0), // origin
anchor: new google.maps.Point(0, 0) // anchor
};
var marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: true, // enables drag & drop
animation: google.maps.Animation.DROP
icon: icon
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I have problems with maps showing markers from a MySql database.
Map doesn't show, but I can see the map starts to initialize. It doesn't show any markers on it.
I am using the same map, showing only one lat/long from a mysql db. It is working perfectly fine without markers, but when I loop to place markersit just doesn't want to show markers.
I really don't want to complicate things with xml tables. I was also using similar code in v2 maps and everything was working fine. This is my code:
<script src="https://maps.googleapis.com/maps/api/js?v=3.11&sensor=false" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
(function (){
var map = new google.maps.Map(document.getElementById('map_canvas'), options);
php starts
while($apa = mysql_fetch_array($result))
{
$lat_map = $apa["lat"];
$lon_map = $apa["lon"];
$adr_apa = $apa["adresa"];
php ends
var options = {
zoom: 12,
center: new google.maps.LatLng(<?php echo $lat_map; ?>, <?php echo $lon_map; ?>),
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControl: false
};
var marker = new google.maps.Marker({
position: new google.maps.LatLng(<?php echo $lat_map; ?>, <?php echo $lon_map; ?>),
map: map,
title: 'Click Me'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow = new google.maps.InfoWindow({
content: '<p><?php echo $adr_apa; ?></p>'
});
infowindow.open(map, marker);
});
<?php } ?>
})();
});
</script>
<?php
echo '
<body>
<div id="map_canvas" style="width: 800px; height: 420px"></div>
</body>
Because you are declaring marker and options javascript variables as many times as elements you have :)
It's not about google maps, its about your JS is not correct and the browser doesn't interpret it.
Move the variable declaration outside the while
var marker, options;
<? php stuff ?>
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.
i am using a php while loop to create a div class multiple times
so every time i have different lat lng
also in every loop i initialize a new map on a different div to create the map
and here is my code
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
var title= "Title";
var lat = <?php echo $lat; ?>;
var lng = <?php echo $lng; ?>;
var myLatlng = new google.maps.LatLng(lat,lng);
var mapOptions = {
zoom: 14,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('beezMapBig<?php echo $tmp;?>'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
}
</script>
everytime the load works with the different lat,lng but i dont have the map 100% loaded
(i cant post image due to low reputation...imagine that the map is loading like 50% with the rest grey blank)
now the weird part is that when i press f12 at any browser to run the console to see some problems/failures the map is getting 100% loaded and resized.
Any ideas why this occurs and why the code is running correctly when run the browser console??
Thanks in advance!!
Had same issue and solved by doing this.
write ready() function. and then place the window resize functions in the initialize method itself (before initializing the map). It will help.
I can use PHP and JS. I have array with 3 elements.
Firstly Im generating div with unique id
<?php $i=0; foreach ($array as $single) : $i++; ?>
<div id="map_<?php echo $i; ?>" style="width: 100%; height: 300px;"></div>
<?php endforeach; ?>
Then im opening script tag like this
<script>
var maps = [];
<?php $i = 0; foreach($array as $single): $i++; ?>
maps.push({
mapContainer: 'map_'+<?php echo $i; ?>,
lat: <?php echo $single['mapa_google']['lat']; ?>,
lng: <?php echo $single['mapa_google']['lng']; ?>,
});
<?php endforeach; ?>
function initMap() {
for(var i = 0; i < maps.length; i++)
{
// The location of Uluru
var uluru = {lat: maps[i].lat, lng: maps[i].lng};
// The map, centered at Uluru
var map = new google.maps.Map(
document.getElementById(maps[i].mapContainer), {zoom: 16, center: uluru}
);
// The marker, positioned at Uluru
var marker = new google.maps.Marker({position: uluru, map: map});
}
}
</script>
On the bottom on my page im using async script
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOURKEY&callback=initMap">
</script>
Of course in my array I have data for 3 google maps.
I have a table with some locations. For example:
ID LAT LNG
1 40.759139 -73.979723
I am trying to get the user country and city from his IP address (let's say I have it and it's Germany, Berlin for example).
And then go over all the locations in my DB and select the ones that are near, or within that city (within the city is better) and display them on a map this way: http://code.google.com/apis/maps/documentation/javascript/examples/event-closure.html
Now i've seen this question:
how do i find near by locations to a given location using google map api
Which is not really what i'm looking for, although it's close.
Anyone knows how I can accomplish what i'm trying to do?
Thanks,
Figured it out, this is how you do it:
Note: $default holds the city lat/lng that you would like to initially display. mapEvents() returns an array with all lat/lng/title of the event.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(<?= $default ?>);
var myOptions = {
zoom: 9,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?php
$pinpoints = mapEvents();
foreach ($pinpoints as $pinpoint) {
$loc = $pinpoint['UA_LAT'] . "," . $pinpoint['UA_LNG'];
echo("
var myLatlng = new google.maps.LatLng(" . $loc . ");
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: '" . $pinpoint['EVENT_NAME'] . "'
});
");
$loc = "";
}
?>
}
</script>