Center Map to Bounds not working - javascript

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.

Related

Google maps Marker dissapear after zoom in function

Hi Im working with HTML5 and I have a simple js function where i set the center of my map and the zoom:
function goToMaxZoom(){
var map=new google.maps.Map(document.getElementById("map"));
map.setCenter(new google.maps.LatLng(12.32323, -3.683639) );
map.setZoom(16);}
everything is going good except for the map markers, they are not displayed
i tryed also to add:
marker.setMap(map);
to make a new one but it doesnt work, even if i add the whole marker build:
var map=new google.maps.Map(document.getElementById("map"),mapProp);
var marker=new google.maps.Marker({
position:(12.32323, -3.683639),
});
So i think im missing something.
Thanks in advance
You will need to create an object of LatLng before adding it to the marker as shown below
var myLatLng = new google.maps.LatLng(12.32323, -3.683639)
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
You can also create the LatLng object using the following constructor
var myLatLng = new google.maps.LatLng({lat: 12.32323, lng: -3.683639});
OR
var myLatLng = {lat: 12.32323, lng: -3.683639};
All three are valid ways to create a LatLng object

Google Maps not centering after dynamically loading latitude/longitude on click

I'm dynamically loading latitude/longitude variables and passing them to the Google Maps Initialize(); function.
function initialize() {
var lat = $('.map_img', '.inview').attr('data-lat');
var lng = $('.map_img', '.inview').attr('data-lng');
var myLatlng = new google.maps.LatLng(lat, lng);
var mapOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map
});
google.maps.event.trigger(map, 'resize');
}
So I'm pulling these coordinates via the data attribute, which is set via a wordpress widget and giving them to Google Maps.
I want to run the function, getting new coordinates every time the user clicks these left/right buttons.
previous
next
$('.btn-prev').click(function () {
//initialize maps script again
initialize();
});
$('.btn-next').click(function () {
//initialize maps script again
initialize();
});
Then the user clicks on a Map image which opens the large map with the new coordinates.
var mapImg = $('.map_img');
var $overlay = $('.overlay'),
resize = true,
map;
mapImg.click(function () {
$overlay.show();
if (resize) {
initialize();
resize = false;
}
});
The problem I'm having is that after the first click the Map is not centered. I had assumed google.maps.event.trigger(map, 'resize'); would solve this problem.
I'm not sure why this is happening so I've created a fiddle to replicate the issue.
http://jsfiddle.net/SEOplay/3CXSs/13/
Help much appreciated.
Try using:
google.maps.event.addDomListener(window, "click", function () {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
Not efficient code because I'm not excatly sure how it fits into your code, but it will recenter the map every time someone clicks somewhere. It should give you some idea of the code you need, if you have any trouble let me know.
JSFiddle (you also seem to have a bug where it doesn't change the map on the first next/prev click.

Google Map V3: fitbounds and center not working together

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);
});

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);

Google Maps don't fully load

I have a somewhat strange problem. I have two maps on my site, a big one and a small one. I want to use the big one to show a route to a certain address. I'm now trying to implement the two maps but get a weird problem. The small map is working fine, but on the big map only a small area of the div is filled with the map, the rest is empty. (See the image.)
I use the following code to display the two maps:
function initialize() {
var latlng = new google.maps.LatLng(51.92475, 4.38206);
var myOptions = {zoom: 10, center: latlng,mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({position: latlng, map:map, title:"Home"});
var image = '/Core/Images/Icons/citysquare.png';
var myLatLng = new google.maps.LatLng(51.92308, 4.47058);
var cityCentre = new google.maps.Marker({position:myLatLng, map:map, icon:image, title:"Centre"});
marker.setMap(map);
var largeLatlng = new google.maps.LatLng(51.92475, 4.38206);
var largeOptions = {zoom: 10, center: largeLatlng,mapTypeId: google.maps.MapTypeId.ROADMAP};
var largeMap = new google.maps.Map(document.getElementById("largeMap"), largeOptions);
var largeMarker = new google.maps.Marker({position: largeLatlng, map:largeMap, title:"Cherrytrees"});
largeMarker.setMap(largeMap);
}
[..]
jQuery(document).ready(function () {
[..]
initialize();
});
What's going wrong here?
EDIT:
Unfortunately the suggestions below doesn't seem to work. The closes i came is to remove the display:none from the elements and set the elements to hide with jquery
[..]
jQuery(document).ready(function () {
[..]
$("#shadow").add($("#shadowContent"),$("#closebar"),$("#content")).hide();
});
With the following result
Yes, #Argiropoulos-Stavros but, Add it as a listener
google.maps.event.addListenerOnce(map, 'idle', function(){
google.maps.event.trigger(map, 'resize');
map.setCenter(location);
});
It will begin re-sizing after, map rendered.
I think you are using v3.
So google.maps.event.trigger(map, "resize");
Also take a look at here
I fixed it!
I made an own function for the largemap and placed it in the callback when the elements are opened
function largeMap(){
var largeLatlng = new google.maps.LatLng(51.92475, 4.38206);
var largeOptions = {zoom: 10, center: largeLatlng,mapTypeId: google.maps.MapTypeId.ROADMAP};
var largeMap = new google.maps.Map(document.getElementById("largeMap"), largeOptions);
var largeMarker = new google.maps.Marker({position: largeLatlng, map:largeMap, title:"Cherrytrees"});
largeMarker.setMap(largeMap);
}
[..]
$("#showRoute").click(function(e){
e.preventDefault();
$("#shadow").add($("#shadowContent"),$("#closebar"),$("#content")).fadeIn(500);
$("#shadowContent").show().css({'width':'750px','top':'25px','left':'50%','margin-left':'-400px'});
$("#closeBarLink").click(function(l){
l.preventDefault();
$("#shadow").add($("#shadowContent"),$("#closebar"),$("#content")).fadeOut(500);
});
largeMap();
});
Thanks anyway!!
call initialize(); function after you box active.
$(document).ready(function () {
$("#shadow").show(function () {
initialize();
})
});
When you're loading in the large map, try adding this at the end of your map code.
map.checkResize();
When Google Maps first renders on your page, it has the dimensions recorded so that it displays the map images in that size. If you're resizing the map dynamically, you need to tell the API to check the new size.
<script type='text/javascript' >
var geocoder, map;
function codeAddress() {
var address= '<?php echo $this->subject()->address; ?>';
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myOptions = {
zoom: 13,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon:'http://rvillage.com/application/themes/rvillage/images/map-marker.png'
});
var infowindow = new google.maps.InfoWindow({ content: 'coming soon' });
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, this);
});
}
});
}
jQuery(document).ready(function () {
codeAddress();
});
</script>
You are using pop up window with jQuery, and I guest you call initialize() function when document is ready ( $(document).ready(function() {initialize(); }) ).
Try call initialize() function after pop up windown showed.
Johnny

Categories

Resources