I am creating a web app that has 2 instances of Google Maps API: one which has many points, and one which only has one point.
They seem to be conflicting with each other, because when I view one page before the other, the other map is not centered in the correct spot.
First Page:
Second Page:
Here is a link to my project: http://jakeserver.com/Apps/BostonLandmarks/B12/index.html
Here is the code that is generating the Google Maps:
var detailsMap = new google.maps.Map(document.getElementById("map_" + this.id), {
zoom: 10,
center: new google.maps.LatLng(landmarkList[rowCount].landmarkGPSNorth, landmarkList[rowCount].landmarkGPSWest),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var detailsInfoWindow = new google.maps.InfoWindow();
var detailsMarker, j;
detailsMarker = new google.maps.Marker({
position: new google.maps.LatLng(landmarksArray[rowCount].landmarkGPSNorth, landmarksArray[rowCount].landmarkGPSWest),
map: detailsMap,
icon: "Icons/red-pin.pdf"
});
detailsInfoWindow.setContent(landmarksArray[rowCount].landmarkName);
detailsInfoWindow.open(detailsMap, detailsMarker);
google.maps.event.addListener(detailsMarker, 'click', (function(detailsMarker, j) {
return function() {
detailsInfoWindow.open(detailsMap, detailsMarker);
}
})(detailsMarker, j));
}
document.getElementById("map_" + this.id).style.height = 300 + "px";
document.getElementById("map_" + this.id).style.width = 300 + "px";
Any ideas?
A long ago I'd a similar problem with a Ajax-Based navigation in a website, each page had a map, the first one working normally, but the next ones had the same problem you're having.
Before displaying the map you should create a new bound object. Just like this:
var bounds = new google.maps.LatLngBounds();
After that. You've to extend the bounds passing your markers positions. Like this:
bounds.extend(marker.position);
And finally, when the map is actually visible and rendered. Run the following lines.
google.maps.event.trigger(secondMapInstance, 'resize');
secondMapInstance.fitBounds(bounds);
Related
Any ideas why my markers aren't clustering? I've tried many different ways and nothing will make them cluster. I realize there might be something wrong with the arguments I'm passing the markerClusterer but I can't find a way to make it work with anything. There's also little to no documentation on markerClusterer.MarkerClusterer (which is required when using unpkg).
function initMap() {
//set map options
var myMapOptions = {
center: {lat: 40.7498024, lng: -73.9774375},
zoom: 12,
}
//fill the html div with a map and pass in map options
var myNewMap = new google.maps.Map(document.getElementById('mymap'), myMapOptions);
//pass in data
myNewMap.data.loadGeoJson('missedConnections.geojson');
//define popup windows
var infowindow = new google.maps.InfoWindow({maxWidth: 750, autopanMargin: 10,});
//create new popup windows on marker click
myNewMap.data.addListener('click', function(event) {
console.log(event);
// set variables
let videourl = event.feature.getProperty('videoURL');
//padding/margin is wonky on mobile vs desktop
let html = '<video style="padding-bottom: 5px; padding-right: 3px;" preload="none" autoplay width=" 90%"><source src="' + videourl + '"></video>';
// show the html variable in the infowindow
infowindow.setContent(html);
infowindow.setPosition(event.latLng);
infowindow.setOptions({pixelOffset: new google.maps.Size(0, -30)});
// move the infowindow up 42 pixels to the top of the default marker icon
infowindow.open(myNewMap);
});
new markerClusterer.MarkerClusterer({myNewMap.data, myNewMap});
}
First, you are using object shorthand incorrectly.
Second, that isn't the interface for the library.
const markerCluster = new MarkerClusterer({ map, markers });
where markers is an array of google.maps.Markers. See MarkerClustererOptions.
Into your html:
<script src="https://unpkg.com/#googlemaps/markerclusterer/dist/index.min.js"></script>
Into your js, code both of these works
var mc = new markerClusterer.MarkerClusterer({ markers, map });
or
new markerClusterer.MarkerClusterer({ markers, map });
I've been looking around for a solution to this problem, but i can't seem to find somthing that solves this. The closest i get is this thread. But this doesn't work.
What i'm trying to do is to run fitbounds based on a set of markers which works fine. But i would also like to center the map based on the users location (the bouncing marker in the plunk) and still keep all markers within the map view.
If i try to setCenter after fitBounds, some markers are outside of the map view.
Is there some nifty way of combining these two functions?
Here's the plunk illustrating the issue.
function initialize() {
var userCenter = new google.maps.LatLng(51.508742, -0.120850);
var userCenterMarker = new google.maps.Marker({
position: userCenter
});
userCenterMarker.setAnimation(google.maps.Animation.BOUNCE);
var mapProp = {
center: userCenter,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var bounds = new google.maps.LatLngBounds();
var markers = getMarkers();
$(markers).each(function() {
bounds.extend(this.position);
this.setMap(map);
});
userCenterMarker.setMap(map);
map.fitBounds(bounds);
setTimeout(function() {
map.setCenter(userCenter);
}, 1500);
}
Thanks!
Simple solution: Add your "user marker" to the bounds, do fitBounds, then decrement the resulting zoom by 1 and center on that marker.
bounds.extend(userCenterMarker.getPosition());
map.fitBounds(bounds);
google.maps.event.addListenerOnce(map,'bounds_changed', function() {
map.setZoom(map.getZoom()-1);
});
working fiddle
More complex solution: Center on the "user marker", check to see if the marker bounds is completely included in the map's current bounds (map.getBounds().contains(markerBounds)), if not, decrement the zoom level by 1.
The above answer didn't work for me. Here's what did:
contained = true;
map.fitBounds(bounds);
map.setCenter(center);
newbounds = map.getBounds();
for (i = 0; i < l; i ++) {
if (!newbounds.contains(markers[i].getPosition())) {
contained = false;
}
}
if (!contained) map.setZoom(map.getZoom() - 1);
Small problem.
So, i'm working with the google maps api for a small project at my internship.
This is how I make my map.
function initMap() {
window.map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 62.323907, lng: -150.109291},
mapTypeId: google.maps.MapTypeId.SATELLITE
});
var bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(62.281819, -150.287132),
new google.maps.LatLng(62.400471, -150.005608));
// The photograph is courtesy of the U.S. Geological Survey.
var srcImage ='https://developers.google.com/maps/documentation/javascript/';
srcImage += 'examples/full/images/talkeetna.png';
overlay = new USGSOverlay(bounds, srcImage, map);
}
The problem I have is the next: I want to determine the zoom, I tried this with:
var zoom = window.map.getZoom();
alert(zoom);
This works! But the only problem I have, this always shows me '12'. And I want to get the current zoom level, after zooming in or out and that doesn't seem to work, it always keeps displaying '12'. How can I fix this?
It is quite simple add a "zoom_changed" listener for your map and get the current zoom of the map
The code can be like
map.addListener("zoom_changed", function() {
alert("Zoom :" + map.getZoom());
});
I have a database of locations which I want to be able to print on a map. Ideally there should be one map with multiple pins for each location you have toggled on. So click a button for location X and it shows up on the map. Click the button for location Y and it shows up on the same map. Click X again and it hides from the map.
Currently I have it so I click on X and the map gets redrawn centered around point X.
Here is the HTML for each button:
<input type='button' data-lat='38.89864400' data-long='-77.05283400'
data-when='20 Aug at 2:00am' value='Location X' class='click' />
The jQuery I'm using is:
jQuery(document).ready(
function initialize() {
jQuery("input.click").click(function() {
showOnMap(jQuery(this).data('lat'), jQuery(this).data('long'), jQuery(this).data('when'));
});
}
);
function showOnMap(lat, long, message) {
var myLatlng = new google.maps.LatLng(lat, long);
var mapOptions = {
zoom: 13,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: message
});
google.maps.event.addDomListener(window, 'load', showOnMap);
}
Is there an easy way to switch from what I have to what I want? I've searched for a while but no one seems to be asking this use case in a browser, just Android (which I'm not doing).
Thanks!
There is an example in the documentation on how to hide/show markers. In short, a marker is:
hidden by setting its map to null
showed by setting its map to map
To do so, you will need to access each marker individually. If you have a definite number of locations, it can be done by naming them with different names (eg var markerLocationX, var markerLocationY, etc). Otherwise, the markers need to be stored in an array.
Supposing you have a definite number of known locations to toggle the markers, your javascript code may look like this:
function toggleMarker(markerName) {
if (markerName.getMap() == null) {
markerName.setMap(map);
} else {
markerName.setMap(null);
}
}
I'm a beginner in google maps and JavaScript.
I'm creating a random markers on google map using Maps API V3, I want to create a list on the side that contain all Markers Id so when i click on Marker ID it will zoom in, on the map to show the marker. specifically i want to know how to create that link in javascript
thank you
This answer is from beginner to beginner ;) I like benastan's answer for succinctness and the application of closure, still I'd like to show a more "basic" approach by writing functions.
I don't feel qualified to talk about closures and function scopes, but I can say from experience these closure "wrappers" prevent unexpected behavior from functions called within loops or within other functions. One such bug could be a loop iterator value ending up all the same value (last iteration) or undefined. (my own example)
Link to full code: http://jsfiddle.net/WaWBw/
Click on the map to place markers, and clicking on markers or links on the side zooms in.
function addMarker(pos) {
var marker = new google.maps.Marker({
map: map,
position: pos
});
markers.push(marker);
count = markers.length - 1;
addMarkerListener(marker, count, 6);
makeDiv(count, 4, "Marker #");
count++;
}
function addMarkerListener(marker, index, zoomLevel) {
google.maps.event.addListener(marker, 'click', function(event) {
zoomIn(index, zoomLevel);
});
}
function makeDiv(index, zoomLevel, content) {
document.getElementById("sidebar").innerHTML += '<div onclick="zoomIn(' + index + ',' + zoomLevel + ')">' + content + ' ' + index + '</div>';
}
function zoomIn(index, zoomLevel) {
map.setCenter(markers[index].getPosition());
map.setZoom(zoomLevel);
}
Say you have a set of lat/lng coordinates:
var coords = [[32, -70], [50, -10], [0, 20]];
Loop through the coordinates, plotting the marker on your map and generating the list items. Bind the click handler at the same time:
var tpl = 'Click here to view a point';
// Loop through coordinates.
for (var i in coords) {
// Create a closure.
(function() {
var pt = coords[i],
latlng = new google.maps.LatLng(pt[0], pt[1]),
marker = new google.maps.Marker({
position: latlng,
map: map // variable containing your google map.
}),
elm = document.createElement('li');
elm.innerHTML = tpl;
// When you click the list item, set map center to latlng of marker.
elm.onclick = function() {
map.setCenter(latlng);
};
document.body.appendChild(elm);
})();
}