want to load multiple google maps with loop - javascript

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.

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!

Use advanced custom fields value in js for google maps marker

I want to use advanced custom fields to place a Google Map icon. I prefer using the repeater field, but first i'am trying to accomplish a regular field. Image field output is url. I don't understand what i'm doing wrong?
Here is a snippet from my code:
<script>
<?php $image = get_field('marker'); ?>
function initialize() {
//add map, the type of map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: new google.maps.LatLng(52.355692, 5.619524),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//add locations
var locations = [
['Hotspot1', 52.355889, 5.619535,'<?php echo $image ;?>'],
['Hotspot2', 52.354349, 5.618924,'$get_google_map']
];
//declare marker call it 'i'
var marker, i;
//declare infowindow
var infowindow = new google.maps.InfoWindow();
//add marker to each locations
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: locations[i][3]
});
//click function to marker, pops up infowindow
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=hidden&callback=initialize">
</script>
<?php endwhile; ?>
</div>
<?php endif; ?>
Thanks in advance,
Gino
Missing an echo for $get_google_map. Not sure what that represents either since it's not defined
var locations = [
['Hotspot1', 52.355889, 5.619535,'<?php echo $image ;?>'],
['Hotspot2', 52.354349, 5.618924,'$get_google_map']
];
Should be
var locations = [
['Hotspot1', 52.355889, 5.619535,'<?php echo $image ;?>'],
['Hotspot2', 52.354349, 5.618924,'<?php echo $get_google_map ;?>']
];
Inspect the output in browser source to see what the locations array actually looks like or log it to your console with console.log(locations)
Thanks for your quick reply. I changed the code into this:
<script>
<?php $image = get_field('marker'); ?>
function initialize() {
//add map, the type of map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15
, center: new google.maps.LatLng(52.355692, 5.619524)
, mapTypeId: google.maps.MapTypeId.ROADMAP
});
//add locations
var locations = [
['Hotspot1', 52.355889, 5.619535, '<?php echo $image ;?>']
, ['Hotspot2', 52.354349, 5.618924, '<?php echo $image ;?>']
];
Because $get_google_map was from previous testing. But unfortunately the
$image doesn't output anything.

GoogleMaps v3 - map doesn't want to load markers from mysql db

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

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

Changing marker at certain zoom level - Google Maps API 3

I have a map that loads and displays (correctly) a bunch of markers. The amount of markers are unlimited, so they are created before the map is initialized by running a bit of PHP in the javascript (the markers come from a database).
I want to know, if it is possible to change the marker from a simple dot, to something else when a certain zoom level is reached?
Here is some code:
<script>
var <?php echo $clinic_string; ?>; //string with marker names
var map;
function initialize() {
var kzn = new google.maps.LatLng(-28.459033,30.217037);
var mapOptions = {
zoom: 7,
center: kzn,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
<?php foreach($jsdata as $data) : ?>
marker_<?php echo $data['id'];?> = new google.maps.Marker({
position: new google.maps.LatLng(<?php echo $data['location'];?>),
map: map,
icon: 'images/reddot.gif'
});
<?php endforeach; ?>
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Let's say my zoom level reaches level 15, it needs to change the icon to images/clinic.gif.
Is this possible? And if so, how can I achieve this?
Not too hard. You need an event listener for the map object's zoom_changed event. And you can change the markers icons using the marker's setIcon function. Something like:
<?php foreach($jsdata as $data) : ?>
marker_<?php echo $data['id'];?> = new google.maps.Marker({
position: new google.maps.LatLng(<?php echo $data['location'];?>),
map: map,
icon: 'images/reddot.gif'
});
map.addListener('zoom_changed', function() {
if (map.getZoom() >= 15) {
marker_<?php echo $data['id'];?>.setIcon('images/clinic.gif');
} else { // assuming you want to change it back if they zoom back out
marker_<?php echo $data['id'];?>.setIcon('images/reddot.gif');
}
});
<?php endforeach; ?>
In fact rather than have X number of 'zoom_changed' event listeners, I think I'd rather have one array for all my markers. Then just have one event listener function, which loops over all those markers.
markers = [];
<?php foreach($jsdata as $data) : ?>
marker_<?php echo $data['id'];?> = new google.maps.Marker({
position: new google.maps.LatLng(<?php echo $data['location'];?>),
map: map,
icon: 'images/reddot.gif'
});
markers.push(marker_<?php echo $data['id'];?>);
<?php endforeach; ?>
map.addListener('zoom_changed', function() {
var image;
if (map.getZoom() >= 15) {
image = 'images/clinic.gif';
else { // assuming you want to change it back if they zoom back out
image = 'images/reddot.gif';
}
for (var i = 0; i < markers.length; i++) {
markers[i].setIcon(image);
}
});

Categories