Changing marker at certain zoom level - Google Maps API 3 - javascript

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);
}
});

Related

how to indicate multiple custom marker on map using fetch lat and long data from mysql db

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>

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

want to load multiple google maps with loop

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.

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

Categories