Google Maps Api v3 - Multiple Info Windows with custom content - javascript

I have finally managed to add multiple markers with custom icons to my Googlemap.
The next step would be to add an individual Infowindow for each marker.
Unfortunatelly i cant figure out how.
Here is my script so far:
<script type="text/javascript">
var offender_locations = [
["10010", "http://localhost/safenation/img/map_offender_icon.png"],
["10001", "http://localhost/safenation/img/map_visitor_icon.png"]
];
var myOptions = {zoom: 10,center: latlng,mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("elementid"), myOptions);
var latlng = new google.maps.LatLng(0, 0);
var marker;
var i;
for (i = 0; i < offender_locations.length; i++) {
var infowindow = new google.maps.InfoWindow();
var geocoder_map = new google.maps.Geocoder();
var address = offender_locations[i][0];
var icon = offender_locations[i][1];
geocoder_map.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: map.getCenter(),
icon: icon
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(offender_locations[i][1]);
infowindow.open(map, marker);
}
})(marker, i));
} else {alert("The requested offender is not mappable !")};});
}
</script>
I think there now is a problem with the loop. When i try:
var icon = offender_locations[1][1];
all icons are "map_offender_icon.png"
When I use :
var icon = offender_locations[i][1];
nothing changes and all icons are still "map_offender_icon.png"
It seems the var offender_locations[i][1]; is not changing accordingly. The var offender_locations[i][0]; changes accordingly.

Your marker variable is local to your for loop which is not visible outside the loop so the statement
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker, i)
is not able to set the listener for your marker.
Best way is include your Info window initialization inside your loop to set listeners to your entire markers.
Hope this helps.

The problem has been solved!
Working script:
Javascript Loop - 2nd variable Not Displaying
(Extracted from edit to the original question)

Related

Multiple markers working on my local server but markers not working on my live site. http://www.sierracrestweb.com/dev/

Here is the code below, Perfectly display the purple icon on my local server but markers not shown on my website, I search on google and try alternate method but still facing this problem, I guess it is due to Multiple loading API Key errors, but if this How to resolve this error? because I already remove all the script but still face the problem.
<script>
var map;
var marker;
var infowindow;
var red_icon = 'http://maps.google.com/mapfiles/ms/icons/red-dot.png' ;
var purple_icon = 'http://maps.google.com/mapfiles/ms/icons/purple-dot.png';
var locations = <?php get_all_locations() ?>;
function initMap() {
var america = {lat: 37.09024, lng: -95.712891};
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById('map'), {
center: america,
zoom: 7
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var i ;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i]
[2]),
icon : purple_icon,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
<script async defer
src="https://maps.googleapis.com/maps/api/js?
language=en&key=APIKEY&callback=initMap">
</script>
If the marker creation is working on your local but not on server then it is probably not related to the code itself.
I think that the issue is with this line.
var locations = <?php get_all_locations() ?>;
Most likely this function is returning a blank array due to which no markers are plotted on the map.
Try printing out the value of the returned array in the console to ensure that you are indeed getting the correct location array.
var locations = <?php get_all_locations() ?>;
console.log(locations);

Google maps API recenter my map

My code for the initialization of the API looks like so:
jQuery(function($) {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
});
function initialize() {
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
// Multiple Markers
var markers = [
//php code to get markers from DB
];
// Info Window Content
var infoWindowContent = ['some text here'];
// 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]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
//push markers to mapMarkers array.
mapMarkers.push(marker);
// 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);
}
}
Problem is I dont want the map to be centered around my markers I get from the database anymore. But if I delete map.fitBounds(bounds); and try to use map.setCenter({lat: -34, lng: 151}); I get a blank screen. If I even touch anything in this code I get a blank screen instead of my map!
A map must have a zoom.
You didn't initially set a zoom for the map.
When you use fitBounds() the zoom will be set automatically, but when you didn't use it the zoom is still missing.
Solution: set a zoom in mapOptions

Hide Markers on Click with Google Maps API

I am building a search form using Google Maps Javascript V3 API. I would like to add some filters that will hide certain types of markers on the map when clicked. The markers to hide are represented with
locations[i][11] == 'Other'
HTML:
Hide Other Markers
JavaScript:
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
center: { lat: 48.509532, lng: -122.643852}
};
var map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
var locations = <?php echo json_encode($locations_array); ?>;
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
animation: google.maps.Animation.DROP,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var content = '';
infowindow.setContent(content);
infowindow.open(map, marker);
}
})(marker, i));
google.maps.event.addDomListener(document.getElementsByClassName('hideOtherMarkers')[0], 'click', function() {
if (locations[i][11] == 'Other') {
marker.setVisible(false); // maps API hide call
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
When I click the link nothing fires, verified with alerts. I also tried google.maps.event.addListener (without Dom) with no success.
As commented by geocodezip this approach will not work, because i will always point behind the end of locations. Additionally this would hide at best 1 marker (the last marker that has been created).
Possible approach:
Store the visible-state of the markers in a MVCObject:
map-options:
var mapOptions = {
center: { lat: 48.509532, lng: -122.643852}
//that's the property where we store the state
visibility:new google.maps.MVCObject
};
inside the loop, after the creation of marker:
//when the state is not set yet, set it
if(typeof map.get('visibility').get(locations[i][11])==='undefined'){
map.get('visibility').set(locations[i][11],true);
}
//bind the visible-property of the marker to the state
marker.bindTo('visible',map.get('visibility'),locations[i][11]);
add the listener(outside of the loop):
google.maps.event.addDomListener(
document.getElementsByClassName('hideOtherMarkers')[0],
'click',
function() {
//simply set the desired property of the MVCObject to false
map.get('visibility').set('Other',false);
});
Demo: http://jsfiddle.net/doktormolle/5L2392mL/

Getting data stored in additional field of googlemap's marker

I'm working with google maps api and javascript which I am not much familiar with. Here's the code I use to draw markers on my map. I get Latitudes and Longitudes from my database:
var geocoder;
var map;
var jsonStr = '<?php echo json_encode($arajka) ?>';
var LatLong = JSON.parse(jsonStr);
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
center: new google.maps.LatLng(50.000001, 20.000001),
zoom: 12
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var marker = [];
for(var i=0;i<LatLong.length;i++){
var LatLong1 = new google.maps.LatLng(LatLong[i].lat, LatLong[i].lon);
marker.ajdi=LatLong[i].id; // storing additional data (I need to get it when user clicks on certain marker)
marker.push(new google.maps.Marker({position: LatLong1, map: map, title: LatLong[i].login}));
}
// trying to set some listener but it fails.
google.maps.event.addListener(marker, 'click', function() {
map.setZoom(8);
map.setCenter(marker.getPosition());
alert("ASDASDASD" + marker.ajdi);
});
}
So, this listener doesn't work, I don't know why. Well, I expect that it doesn't exactly know what marker is it about. When I tried to do it with a single one, like in tutorial, it worked properly. I don't know what to do when I have this array. Any suggestions please?
You have several mistakes in your code:
As #Hollister mentions, marker is an array, so you need to put the addListener call inside the loop;
You have to store the additional marker data into the marker, not into the marker array;
you have to use this in the listener, not marker.
for(var i=0;i<LatLong.length;i++){
var LatLong1 = new google.maps.LatLng(LatLong[i].lat, LatLong[i].lon);
var this_marker = new google.maps.Marker({position: LatLong1, map: map, title: LatLong[i].login});
this_marker.ajdi=LatLong[i].id; // storing additional data (I need to get it when user clicks on certain marker)
marker.push(this_marker);
// trying to set some listener but it fails.
google.maps.event.addListener(this_marker, 'click', function() {
map.setZoom(8);
map.setCenter(this.getPosition());
alert("ASDASDASD" + this.ajdi);
});
}

Markers won't show on google maps

I need to place multiple markers on a google map. Here's the problem: I have an array of latitude/longitude data. I need to make a marker appear on the map for each lat/lng pair. But it won't. If I ask the function to print out the coordinates instead of marking them on the, map, it works fine. I don't get an error message either way, so I'm stuck. The page displays the map but without any markers. Here's the code of the function that should add markers:
//adds markers to the map
function addMarkers(locarray) {
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locarray.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locarray[i][0], locarray[i][1]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent('some words');
infowindow.open(map, marker);
}
})(marker, i));
}
}
Here's the initialize function (called on body load):
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = codeAddress("<?php echo $_POST['postal']; ?>");
var myOptions = {
zoom: 11,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
geocoder and map are declared as global variables. The codeAddress function returns lat and lng of the place I want to center the map around, it's been tested and works perfectly. It is NOT the problem, I'm leaving it out to simplify and keep PHP out of this.
And here is the script that declares the array and calls the addMarkers function:
<script type='text/javascript'>
var locations = [
[-33.890542, 151.274856],
[-33.923036, 151.259052],
[-34.028249, 151.157507]
];
addMarkers(locations)
</script>
Does anyone see anything wrong with this?

Categories