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);
Related
I have a Google Map on my website and I am also using a Custom marker to mark the location of the business. I want to bring the icon about 100px to the left as it's currently center of the map... How can I do this?
My code:
function initMap() {
var LatLng = {
lat: REMOVED, lng: REMOVED
};
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 15,
center: LatLng
});
var image = 'REMOVED';
var customMarker = new google.maps.Marker({
position: LatLng,
map: map,
icon: image
});
}
You've almost done. The problem is that you are centering the map in the same position than your marker.
So, set another LatLang for your marker or center the map in another position.
var markerLatLang={lat: WHATEVER, lng: WHATEVER}
var customMarker = new google.maps.Marker({
position: markerLatLang,
map: map,
icon: image
});
Checkout this for further information.
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.
I have a google map with hundreds of markers. I would like the map to center on the users location - preferably with a button click. Currently, I have it centering on page load but with one problem - it clears out all of the markers when it centers on location. I assume this is because of how I'm calling the script. The map container's id is 'map4'.
How can I make this script work without clearing the existing markers? Any help would be greatly appreciated.
<script>
var map; // Google map object
// Initialize and display a google map
function Init()
{
// HTML5/W3C Geolocation
if ( navigator.geolocation )
navigator.geolocation.getCurrentPosition( UserLocation );
// Default to Sherman Oaks
else
ShowLocation( 38.8951, -77.0367, "Sherman Oaks, CA" );
}
// Callback function for asynchronous call to HTML5 geolocation
function UserLocation( position )
{
ShowLocation( position.coords.latitude, position.coords.longitude, "This is your Location" );
}
// Display a map centered at the specified coordinate with a marker and InfoWindow.
function ShowLocation( lat, lng, title )
{
// Create a Google coordinate object for where to center the map
var latlng = new google.maps.LatLng( lat, lng );
// Map options for how to display the Google map
var mapOptions = { zoom: 12, center: latlng };
// Show the Google map in the div with the attribute id 'map-canvas'.
map = new google.maps.Map(document.getElementById('map4'), mapOptions);
// Place a Google Marker at the same location as the map center
// When you hover over the marker, it will display the title
var marker = new google.maps.Marker( {
position: latlng,
map: map,
title: title
});
// Create an InfoWindow for the marker
var contentString = "<b>" + title + "</b>"; // HTML text to display in the InfoWindow
var infowindow = new google.maps.InfoWindow( { content: contentString } );
// Set event to display the InfoWindow anchored to the marker when the marker is clicked.
google.maps.event.addListener( marker, 'click', function() { infowindow.open( map, marker ); });
}
// Call the method 'Init()' to display the google map when the web page is displayed ( load event )
google.maps.event.addDomListener( window, 'load', Init );
</script>
If I understand you correctly, it seems you already have created a map, populated with markers AND THEN you want to center the VERY SAME map. If that's the case, your ShowLocation() function needs to be modified. The reason is that this line
map = new google.maps.Map(document.getElementById('map4'), mapOptions);
creates a fresh new instance of map (replacing any existing map in that container, if the provided map container is the same).
So your problem is that you are creating and centering a new map, instead of just centering the old one.
Just modify the centering function to work with an existing map:
function ShowLocation( lat, lng, title , map)
{
// Create a Google coordinate object for where to center the map
var latlng = new google.maps.LatLng( lat, lng);
//Working with existing map instead of creating a new one
map.setCenter(latlng);
map.setZoom(12);
// Place a Google Marker at the same location as the map center
// When you hover over the marker, it will display the title
var marker = new google.maps.Marker( {
position: latlng,
map: map,
title: title
});
// Create an InfoWindow for the marker
var contentString = "<b>" + title + "</b>"; // HTML text to display in the InfoWindow
var infowindow = new google.maps.InfoWindow( { content: contentString } );
// Set event to display the InfoWindow anchored to the marker when the marker is clicked.
google.maps.event.addListener( marker, 'click', function() { infowindow.open( map, marker ); });
}
And when calling the ShowLocation function, it's 4th parameter would be the google.maps.Map object you created when adding the markers. You cannot reference map only by knowing it's containing element's id, you need the reference for it.
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.
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);
});