Google Map V3: fitbounds and center not working together - javascript

The following code show on a map a church and a priest:
var churchLatLng = new google.maps.LatLng(53.4, 0.14);
var mapOptions = {
center: churchLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
myMap = new google.maps.Map(document.getElementById('myDiv'), mapOptions);
var bounds = new google.maps.LatLngBounds();
// Setting church marker
new google.maps.Marker({
position: churchLatLng,
map: myMap,
});
bounds.extend(churchLatLng);
var priestLatLng = new google.maps.LatLng(51.2,0.13);
new google.maps.Marker({
position: priestLatLng,
map: myMap
});
bounds.extend(priestLatLng);
myMap.fitBounds(bounds);
The code use both the option "center" to center the church at the center of the map, and the function "fitBounds" to fit all the markers (church and priest only in this case).
The result is that the map border is set to encompass the two markers, but the option "center" doesn't work anymore and is ignored.
What I want is setting the bounds, but at the same time showing the church at the centre of the map.
How can I accomplish this?

call myMap.fitBounds to set the bounds to show all the markers.
change the map to center where you like (on the church)
add a listener to the bounds_changed event, when that fires, check to see if the map bounds contains the priest marker, if it does, you are done.
if the priest marker is not contained by the map bounds, zoom out one level (map.setZoom(map.getZoom()-1)).
myMap.fitBounds(bounds);
google.maps.event.addListenerOnce(myMap,'bounds_changed',function() {
google.maps.event.addListenerOnce(myMap, 'center_changed', function() {
if (!myMap.getBounds().contains(priestLatLng)) {
myMap.setZoom(myMap.getZoom()-1);
}
});
myMap.setCenter(churchLatLng);
});

Try to use an eventlistener and wait for the bounds to change (it works asynchronous).
Something like:
google.maps.event.addListenerOnce(myMap, 'bounds_changed', function(event) {
myMap.setCenter(churchLatLng);
});

Related

Google Maps not centering on additional maps after expanding jQuery UI accordion

I have a Google Map inside a JavaScript Accordion UI, and it puts a pin in the passed latitude/longitude and "centers" on that pin.
For the first map, it works. When you click either of the other two, it seems to put the (base of the) pin in the top-left corner of the map. I'm already calling resize, as you can see in my code.
Here is a fiddle which demonstrates the issue: http://jsfiddle.net/myingling/1c4bjsff/2/
I'm sure this is something simple, but what am I missing?
You need to save the center of each map, then set it once the new accordion is activated (and that map has a size, when the map/accordion is hidden, it has a computed size of zero, so the marker is centered in the upper left hand corner of the div).
One option:
var maps = [];
jQuery("#accordion").accordion({
change: function(event, ui) {
for (var i = 0; i < maps.length; i++) {
google.maps.event.trigger(maps[i], 'resize');
maps[i].setCenter(maps[i]._center);
}
}
}).find('.map').each(function(i, o) {
var latLong = new google.maps.LatLng(
jQuery(this).data("lat"), jQuery(this).data("long"));
var map = new google.maps.Map(o, {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROAD,
center: latLong
});
maps.push(map);
var marker = new google.maps.Marker({
position: latLong,
map: map,
title: jQuery(this).data('time')
});
google.maps.event.trigger(map, 'resize');
map.setCenter(latLong);
map._center = latLong;
jQuery(o).data('map', map);
});
proof of concept fiddle

How can I change marker position eventually in google maps api?

I have a problem with google maps api, when I change the marker position constantly, this leave a trace on map and I need move the marker without leaving a trace.
I actually get the latitude and the longitude from a database in firebase and need represent the route of a car.
var mapOptions = {
center: new google.maps.LatLng(20.615977, -103.339358),
zoom: 12
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
firebase.database().ref('route').on('value', function(data) {
var start = new google.maps.Marker({
position: {lat: latitud, lng: longitud},
map: map,
icon: '../icon/car.png'
});
var myLatlng = new google.maps.LatLng(data.val().latitude, data.val().longitude);
start.setPosition(myLatlng);
start.setMap(map);
});
You're creating a new marker in every event. Instead, create the marker before the event handler (and call setMap there), and in your handler, just do setPosition() to the data's new lat/lng.

Google marker disappearing when use setPosition to change position

I have a simple google maps , and I am creating a simple map with a marker with the below code:
var mapElement = document.getElementById('hr-map');
// Create the Google Map using our element and options defined above
var map = new google.maps.Map(mapElement, mapOptions);
// Let's also add a marker while we're at it
var marker = new google.maps.Marker({
position: new google.maps.LatLng(25.098353, 55.156124),
map: map,
title: 'HR',
scrollwheel: false,
icon: 'images/res/map-marker.png'
});
Now all I wanted to do is move the marker from the center of the map to somewhere below the center, I googled and check the below two links, one is a SO question and the fiddle demonstrating changing the marker position.
FIDDLE HERE
SO THREAD
Now I used the same line of code used in the fiddle and also in the SO thread and wrote the below line of code:
marker.setPosition(google.maps.LatLng(25.098353, 55.156124));
But adding the above line of code actually makes the entire marker disappear. So now my code looks line below:
var mapElement = document.getElementById('dynamic-hr-map');
// Create the Google Map using our element and options defined above
var map = new google.maps.Map(mapElement, mapOptions);
// Let's also add a marker while we're at it
var marker = new google.maps.Marker({
position: new google.maps.LatLng(25.098353, 55.156124),
map: map,
title: 'Dynamic HR',
scrollwheel: false,
icon: 'images/res/map-marker.png'
});
marker.setPosition(google.maps.LatLng(25.098353, 55.156124));
So well why is my marker disappearing in the first place ? Is there any solution to this ?
You are missing the new keyword. You need to create a new instance of LatLng object before using it.
marker.setPosition(new google.maps.LatLng(25.098353, 55.156124));

Center Map to Bounds not working

I am trying to center map to fit all markers. There are lots of example of this, and seems reasonably easy, but I just can't get it to work. Can anyone see what I am doing wrong?
The map can be tested here: http://www.lymphoedema.org.au/the-register/find-a-practitioner-test/ [[Search within 40kms of 3000; then click Map to view the map]].
The map is zoomed right out, and the markers are up in the very top left corner of the map.
Can anyone see what I am doing wrong?
Thank you!
<script type='text/javascript'>
var markers = [];
var marker;
console.log('About to setup map');
//setup the map
function initialize() {
var mapProp = {
draggable: true,
scrollwheel: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("resultmap-canvas"), mapProp);
// show markers
var myLatLng = {lat: -37.8757303, lng: 145.1277893};
var marker6610 = new google.maps.Marker({
position: myLatLng,
map: map
});
marker6610.setValues( {profileid: 6610, directoryid: 2} );
markers.push(marker6610);
var myLatLng = {lat: -38.0034790, lng: 145.1198805};
var marker5316 = new google.maps.Marker({
position: myLatLng,
map: map
});
marker5316.setValues( {profileid: 5316, directoryid: 2} );
markers.push(marker5316);
//set map bounds
var bounds = new google.maps.LatLngBounds();
for(i=0;i<markers.length;i++) {
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
}
//execute the map creation
initialize();
// trigger map resize event when map tab is displayed
$("#mapTab").on('shown.bs.tab', function() {
google.maps.event.trigger(map, 'resize');
});
</script>
Your code works fine when tested out of a bootstrap tab. So I guess the resize trigger has some implication in the issue.
Try this way:
Declare your bounds variable outside of the initialize function scope (that is where you define your marker and markers variables). By the way, you are missing the map variable declaration too.
var markers = [];
var marker;
var bounds = new google.maps.LatLngBounds();
var map; // missing in your original code
Then fit the bounds too in the bootstrap shown event:
// trigger map resize event when map tab is displayed
$("#mapTab").on('shown.bs.tab', function() {
google.maps.event.trigger(map, 'resize');
map.fitBounds(bounds); // add this line to your code
});
Don't forget to also remove the var declaration here:
//set map bounds
var bounds = new google.maps.LatLngBounds();
Should now be:
//set map bounds
bounds = new google.maps.LatLngBounds();
This is untested but that's all I can think of right now. Let me know if it works or not.

How to move the center position of google map

I am creating a google map in a script with the following code -
var mapElement,
parent,
mapOptions,
map,
marker,
latLong,
openMarker;
parent = document.getElementsByClassName('parent')[0];
mapElement = document.createElement('div');
latLong = new google.maps.LatLng(some_lat_from_db, some_long_from_db);
mapOptions = {
center: latLong,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(mapElement, mapOptions);
marker = new google.maps.Marker({
position: latLong,
map: map,
title: 'some title'
});
openMarker = function () {
var infowindow = new google.maps.InfoWindow();
infowindow.setContent('Some Content');
infowindow.open(map, marker);
};
google.maps.event.addListener(marker, 'click', openMarker);
parent.appendChild(mapElement);
openMarker();
When using this code, the infowindow that opens up by default goes outside the map viewport, so it's not visible. I first tried to reduce the size of the info window but that didn't work out. So I thought to move the center of the map a bit so that the info window remains in the viewport.
So, how can I move the center by some pixels so that the info window remains in the viewport?
You can use .setCenter() to move the center of the map
map.setCenter(marker.getPosition());
Update
Convert the LatLng with .fromLatLngToDivPixel() into a Point add an offset and convert it back into a LatLng with .fromDivPixelToLatLng()
forget all that crap this is what works if you want to reuse a google map marker or move a google map marker, or recenter a google map marker.
var lo = <yourval>;
var la = <yourval>;
var midpoint = {lat:la, lng:lo };
marker.setPosition(midpoint);
if you want to destroy a google maps marker or delete a google maps marker
marker.setMap(null);

Categories

Resources