I'm having trouble with pins on a Google Map from street addresses. I'd like to place the pins, set the zoom level to the highest required to show all the pins placed (ie zoomed in on the 3 locations in my example) and have the infoWindows on the pins with the content from my array.
I have an array (locations) of addresses[1], along with the information[0] I'd like to place in an InfoWindow. I have the geocoding working, my pins are placed on the map. The map doesn't zoom in on my pins nor does it display the infoWindows.
This is the code I have:
<div id="map" style="background:#db7093;height:600px;width:auto;"></div>
<script type="text/javascript">
var locations = [
["<a href=\"https://example.com/building1/\">Library</a>", " 350 W Georgia St, Vancouver, BC, Canada", 1],
["<a href=\"https://example.com/building2/\">City Hall</a>", "453 W 12th Ave, Vancouver, BC, Canada", 2],
["<a href=\"https://example.com/building3/\">Art Gallery</a>", "750 Hornby St, Vancouver, BC, Canada", 3]
];
</script>
<script type="text/javascript">
function mapAddress(currentLocation, bounds) {
var geocoder = new google.maps.Geocoder();
var marker = new google.maps.Marker();
var address = currentLocation[1];
geocoder.geocode({
"address": address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
if (marker)
marker.setMap(null);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
draggable: false
});
bounds.extend(marker.position);
google.maps.event.addListener(marker, "click", (function(marker, i) {
return function() {
infowindow.setContent(currentLocation[0]);
infowindow.open(map, marker);
}
})(marker, i));
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function initMap() {
window.map = new google.maps.Map(document.getElementById("map"), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
var currentLocation = locations[i];
mapAddress(currentLocation, bounds);
}
map.fitBounds(bounds);
map.panToBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function() {
map.setZoom(14); // Manually setting zoom level, as fitBounds isn't working
google.maps.event.removeListener(listener);
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=[MyGoogleMapsAPIKeyHasBeenRemoved]&callback=initMap"></script>