Cant get fitBounds to work - google-maps

I'm not sure where to include the fit bounds as no matter where I put it, the map is centered on where initMap specifies which is halfway across the world instead of where the markers are.
Calls is just an object array that stores sets of lat/lngs
function initMap()
{
map = new google.maps.Map(document.getElementById('map'),
{
center: { lat: -34.397, lng: 150.644 },
zoom: 12,
scaleControl: true
});
}
// Place Markers on Map
function initMarkers()
{
for (var i = 0; i < Calls.length; i++)
{
var marker = new google.maps.Marker({
position: Calls[i],
map: map
});
}
}
function fit()
{
var bound = new google.maps.LatLngBounds();
for (var i in Calls)
{
bound.extend(Calls[i].getPosition());
}
map.fitBounds(bound);
}
// Initialize GoogleMap on Page Load
window.onload = function()
{
initMap();
initMarkers();
fit();
}

The posted code generates a javascript error (not the one originally reported in the question, but that has been removed): Uncaught TypeError: Calls[i].getPosition is not a function. Calls is an array of objects, so it won't have a .getPosition method.
function fit()
{
var bound = new google.maps.LatLngBounds();
for (var i in Calls)
{
bound.extend(new google.maps.LatLng(Calls[i].lat,Calls[i].lng));
}
map.fitBounds(bound);
}
code snippet:
var Calls = [{
lat: 42,
lng: -72
}, {
lat: 40.7127837,
lng: -74.0059413
}, {
lat: 40.735657,
lng: -74.1723667
}];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 12,
scaleControl: true
});
}
// Place Markers on Map
function initMarkers() {
for (var i = 0; i < Calls.length; i++) {
var marker = new google.maps.Marker({
position: Calls[i],
map: map
});
}
}
function fit() {
var bound = new google.maps.LatLngBounds();
for (var i in Calls) {
bound.extend(new google.maps.LatLng(Calls[i].lat, Calls[i].lng));
}
map.fitBounds(bound);
}
// Initialize GoogleMap on Page Load
window.onload = function() {
initMap();
initMarkers();
fit();
}
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

Related

Dynamic marker and infoWindow Google Maps API using Google App Engine parsing through a JSON file

Hi I'm new to stackoverflow (and coding) but I am working on a web-application where I want to add dynamic markers and infowindows based on an extracted JSON file. There are over 200 markers, so they need to be dynamic. I have code that works to add markers but as soon as I add infoWindows it doesn't. Can anybody see why? The output dropped to just one marker and no infoWindow.
Here is my code:
function initMap() {
var myLatLng = {
lat: 26.967,
lng: -99.25
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
$.ajax({
type: 'GET',
url: 'https://us-central1-cloud-calendar-project.cloudfunctions.net/InfoWindow',
success: function(data) {
data = JSON.parse(data)
infowindow = new google.maps.InfoWindow();
for (element in data) {
new google.maps.Marker({
position: {
lat: data[element].lat,
lng: data[element].lon
},
map: map,
title: element
});
infowindow.setContent(data[element].country);
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
}
});
}
I saw a post on stackoverflow with a similar question and tried it that way as well but didnt get any markers.
function initMap() {
var myLatLng = {
lat: 26.967,
lng: -99.25
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
$.ajax({
type: 'GET',
url: 'https://us-central1-cloud-calendar-project.cloudfunctions.net/InfoWindow',
success: function(data) {
var json = data = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
point = new google.maps.LatLng(json[i].lat, json[i].lon);
contentString = json[i].Country;
addMarkers(point, contentString);
}
}
});
function addMarkers(point, contentString) {
marker = new google.maps.Marker({
position: point,
map: map
});
infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.push(marker);
infos.push(infowindow);
for (var j = 0; j < markers.length; j++) {
google.maps.event.addListener(markers[j], 'click', function() {
infos[j].open(map, markers[j]);
})
}
}
}
The output of my JSON file looks like this:
{
"AA": {
"celsius": 32.27777777777778,
"country": "AA",
"day": "25",
"lat": 12.5,
"lon": -70.017,
"month": "03"
},
...
}
There are a few issues in your code. You should read Using Closures in Event Listeners.
You should set the infowindow content on marker click (not within the loop, as you did)
You should declare the marker variable which is missing
Any variable you are using must be declared, for example for (element in data) should be for (var element in data)
function initMap() {
var myLatLng = {
lat: 26.967,
lng: -99.25
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
$.ajax({
type: 'GET',
url: 'https://us-central1-cloud-calendar-project.cloudfunctions.net/InfoWindow',
success: function(data) {
data = JSON.parse(data)
console.log(data);
infowindow = new google.maps.InfoWindow();
for (var element in data) {
var marker = new google.maps.Marker({
position: {
lat: data[element].lat,
lng: data[element].lon
},
map: map,
title: element
});
google.maps.event.addListener(marker, 'click', (function(marker, element) {
return function() {
var content = 'Country: ' + data[element].country;
content += '<br>Temperature (°C): ' + data[element].celsius;
infowindow.setContent(content);
infowindow.open(map, marker);
}
})(marker, element));
}
}
});
}
initMap();
#map {
height: 180px;
}
<div id="map"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>

Trying to get the marker var out of the foreach loop for markerCluster to work, what is the easiest way of doing this?

I am trying to add MarkerClusters to my map, however my marker variable is within a function with a foreach loop used to retrieve Instagram API data, what is the best possible way to get MarkerClusters working?
I tried wrapping the initMap function around the setMarkers function, putting the markerCluster variable within the setMarkers function and within the foreach loop but it just keeps showing the markers (pictures in my case)
<script>
let coords = document.getElementById("places").innerHTML;
let parts = coords.split(",");
let finalResult = []
while (parts.length) {
let newArr = parts.splice(0, 3);
finalResult.push(newArr);
}
console.log(finalResult)
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {
lat: 52.9,
lng: 101.2
}
});
setMarkers(map);
}
function setMarkers(map) {
finalResult.forEach((place) => {
var image = {
url: place[0],
scaledSize: new google.maps.Size(64, 64),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(32, 32)
};
var shape = {
coords: [1, 1, 1, 20, 18, 20, 18, 1],
type: 'poly'
};
var myLatlng = new google.maps.LatLng(place[1], place[2]);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image,
shape: shape
});
})
var markerCluster = new MarkerClusterer(map, marker,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
</script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
One option is to create the MarkerClusterer inside your setMarkers function, then add the markers to it individually as you create them with the .addMarker method.
function setMarkers(map) {
var markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
finalResult.forEach((place) => {
var image = {
url: place[0],
};
var myLatlng = new google.maps.LatLng(place[1], place[2]);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image,
});
markerCluster.addMarker(marker);
});
proof of concept fiddle
code snippet:
let coords = document.getElementById("places").innerHTML;
let parts = coords.split(",");
let finalResult = []
while (parts.length) {
let newArr = parts.splice(0, 3);
finalResult.push(newArr);
}
console.log(finalResult)
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: -38,
lng: 150
}
});
setMarkers(map);
}
function setMarkers(map) {
var bounds = new google.maps.LatLngBounds();
var markerCluster = new MarkerClusterer(map, [], {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
finalResult.forEach((place) => {
var image = {
url: place[0],
};
var myLatlng = new google.maps.LatLng(place[1], place[2]);
bounds.extend(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image,
});
markerCluster.addMarker(marker);
map.fitBounds(bounds);
});
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
<div id="places" style="display:none">https://maps.google.com/mapfiles/ms/micons/blue.png,-31.563910,147.154312, https://maps.google.com/mapfiles/ms/micons/blue.png,-33.718234,150.363181, https://maps.google.com/mapfiles/ms/micons/blue.png,-33.727111,150.371124, https://maps.google.com/mapfiles/ms/micons/blue.png,-33.848588,151.209834,https://maps.google.com/mapfiles/ms/micons/blue.png,-33.851702,151.216968,
https://maps.google.com/mapfiles/ms/micons/blue.png,-34.671264,150.863657, https://maps.google.com/mapfiles/ms/micons/blue.png,-35.304724,148.662905, https://maps.google.com/mapfiles/ms/micons/blue.png,-36.817685,175.699196,https://maps.google.com/mapfiles/ms/micons/blue.png,-36.828611,175.790222,
https://maps.google.com/mapfiles/ms/micons/blue.png,-37.750000,145.116667, https://maps.google.com/mapfiles/ms/micons/blue.png,-37.759859,145.128708, https://maps.google.com/mapfiles/ms/micons/blue.png,-37.765015,145.133858,https://maps.google.com/mapfiles/ms/micons/blue.png,-37.770104,145.143299,
https://maps.google.com/mapfiles/ms/micons/blue.png,-37.773700,145.145187, https://maps.google.com/mapfiles/ms/micons/blue.png,-37.774785,145.137978, https://maps.google.com/mapfiles/ms/micons/blue.png,-37.819616,144.968119, https://maps.google.com/mapfiles/ms/micons/blue.png,-38.330766,144.695692,
https://maps.google.com/mapfiles/ms/micons/blue.png,-39.927193,175.053218, https://maps.google.com/mapfiles/ms/micons/blue.png,-41.330162,174.865694, https://maps.google.com/mapfiles/ms/micons/blue.png,-42.734358,147.439506, https://maps.google.com/mapfiles/ms/micons/blue.png,-42.734358,147.501315,
https://maps.google.com/mapfiles/ms/micons/blue.png,-42.735258,147.438000, https://maps.google.com/mapfiles/ms/micons/blue.png,-43.999792,170.463352,
</div>

Adding markers to Google Maps in a loop doesn't work

I'm trying to load several random markers to a Google Map. When I run the following script it only produces a single marker which is referenced in the map init function. I'm totally stumped. The non-area is after the declaration of the addMarker function. I know the loop is running via console.log but it's not placing markers on the map.
var map;
var northeast;
var southeast;
var northwest;
var southwest;
var markers = [];
var lat = (Math.random() * (80 - -80) + -80).toFixed(7) * 1;
var lng = (Math.random() * (170 - -170) + -170).toFixed(7) * 1;
function initMap() {
var randomMarker = {lat: lat, lng: lng};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: {lat: 0, lng: 0},
mapTypeId: 'terrain',
disableDefaultUI: true,
zoomControl: false,
scrollwheel: false,
draggable: false
});
// Adds a marker at the center of the map.
addMarker(randomMarker);
}
// Adds a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
animation: google.maps.Animation.DROP,
icon: "https://maps.google.com/mapfiles/ms/icons/blue.png",
scaledSize: new google.maps.Size(22, 22)
});
for (var i = 0; i < 10; i++) {
markers.push(marker);
}
}
// Test loop
function testHello() {
for (var i = 0; i < 10; i++) {
console.log("hello world");
}
}
// Sets the map on all markers in the array.
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Checkbox function for Northeast quadrant
$('#neVisible').change(function() {
// this will contain a reference to the checkbox
if (this.checked) {
setMapOnAll(map);
} else {
setMapOnAll(null);
}
});
// Checkbox function for Southeast quadrant
$('#seVisible').change(function() {
// this will contain a reference to the checkbox
if (this.checked) {
setMapOnAll(map);
} else {
setMapOnAll(null);
}
});
// Checkbox function for Northwest quadrant
$('#nwVisible').change(function() {
// this will contain a reference to the checkbox
if (this.checked) {
setMapOnAll(map);
} else {
setMapOnAll(null);
}
});
// Checkbox function for Southwest quadrant
$('#swVisible').change(function() {
// this will contain a reference to the checkbox
if (this.checked) {
setMapOnAll(map);
} else {
setMapOnAll(null);
}
});
The addMarker function is called just once from initMap function.
// Adds a marker at the center of the map.
addMarker(randomMarker);
The addMarker function will create only one marker
// Adds a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
animation: google.maps.Animation.DROP,
icon: "https://maps.google.com/mapfiles/ms/icons/blue.png",
scaledSize: new google.maps.Size(22, 22)
});
for (var i = 0; i < 10; i++) {
markers.push(marker);
}
}
The for loop adds the same marker to the markerArray 10 times.
for (var i = 0; i < 10; i++) {
markers.push(marker);
}
Due to this all markers will get plotted on the same point and it will look like you have just one marker on the map. In order to fix the issue you need to call the addMarker function multiple times and alter it as follows :
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
animation: google.maps.Animation.DROP,
icon: "https://maps.google.com/mapfiles/ms/icons/blue.png",
scaledSize: new google.maps.Size(22, 22)
});
markers.push(marker);
}
This will create a new marker and add it to the markers array.
Edit the initMap function to create random coordinates and add markers at those locations. Try zooming out of the map to view all the markers together.
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: {lat: 0, lng: 0},
mapTypeId: 'terrain',
disableDefaultUI: true,
zoomControl: false,
scrollwheel: false,
draggable: false
});
for (var i = 0; i < 10; i++) {
var lat = (Math.random() * (80 - -80) + -80).toFixed(7) * 1;
var lng = (Math.random() * (170 - -170) + -170).toFixed(7) * 1;
var randomMarker = {lat: lat, lng: lng};
// Adds a marker at the center of the map.
addMarker(randomMarker);
}
}

Not Able to Attach Drag & Dragend Events to Draggable Marker (Cannot read property 'addListener' of undefined)

can you pleas take a look at this code and let me know why I am not able to attach/bind drag and dragend events to the draggable marker?
I am getting
Uncaught TypeError: Cannot read property 'addListener' of undefined
on
marker.addListener('drag', handleEvent);
marker.addListener('dragend', handleEvent);
lines
function initMap() {
var marker;
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
map.addListener('click', function(e) {
placeMarker(e.latLng, map);
});
function placeMarker(position, map) {
marker = new google.maps.Marker({
position: position,
draggable:true,
map: map
});
console.log(marker.position.lat());
}
function handleEvent(event) {
console.log(marker.position.lat());
}
marker.addListener('drag', handleEvent);
marker.addListener('dragend', handleEvent);
}
You are adding the listener to the marker before it exists. Move those definitions into the placeMarker function.
function placeMarker(position, map) {
marker = new google.maps.Marker({
position: position,
draggable: true,
map: map
});
marker.addListener('drag', handleEvent);
marker.addListener('dragend', handleEvent);
console.log(marker.position.lat());
}
proof of concept fiddle
code snippet:
function initMap() {
var marker;
var myLatLng = {
lat: -25.363,
lng: 131.044
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
map.addListener('click', function(e) {
placeMarker(e.latLng, map);
});
function placeMarker(position, map) {
marker = new google.maps.Marker({
position: position,
draggable: true,
map: map
});
marker.addListener('drag', handleEvent);
marker.addListener('dragend', handleEvent);
console.log(marker.getPosition().toUrlValue(6));
}
function handleEvent(event) {
console.log(marker.getPosition().toUrlValue(6));
}
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>

Google maps, changing the map on click - outside the map

I want to change the map (lat and lag) when a div (which is outside the map) is clicked.
I have got it working when the #map div is clicked, however any event outside the map does not get picked up.
This is what I have so far.
var map;
function initMap() {
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 52.9722222,
lng: -3.1622222
},
disableDefaultUI: true,
zoom: 17,
mapTypeControlOptions: {
mapTypeIds: ['roadmap', 'satellite', 'hybrid', 'terrain',
'styled_map'
]
}
});
google.maps.event.addDomListener(mapDiv, 'click', function() {
window.alert('Map was clicked!');
});
var image = 'img/mapmarker.png';
//Associate the styled map with the MapTypeId and set it to display.
map.mapTypes.set('styled_map', styledMapType);
map.setMapTypeId('styled_map');
var marker = new google.maps.Marker({
position: {
lat: 52.9722222,
lng: -3.1622222
},
map: map,
icon: image,
});
}
The map variable that is being initialized is local to the initMap function. You need to initialize the global version:
var map;
function initMap() {
var mapDiv = document.getElementById('map');
// remove the var before map in this line:
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 52.9722222, lng: -3.1622222},
proof of concept fiddle
code snippet:
var map;
function initMap() {
var mapDiv = document.getElementById('map');
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 52.9722222,
lng: -3.1622222
},
disableDefaultUI: true,
zoom: 17,
mapTypeControlOptions: {
mapTypeIds: ['roadmap', 'satellite', 'hybrid', 'terrain',
'styled_map'
]
}
});
google.maps.event.addDomListener(mapDiv, 'click', function() {
window.alert('Map was clicked!');
});
var marker = new google.maps.Marker({
position: {
lat: 52.9722222,
lng: -3.1622222
},
map: map
});
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input type="button" value="Click Me!" onclick="map.setCenter({lat:52.97,lng:-3.16});map.setZoom(15);" />
<div id="map"></div>