Current I have a google maps that will display some markers on the map from my DB... I would like to add a infowindow when the users click on the marker.
I got it to work, but the problem is that it only display on the last marker that was loaded, why is that?
Here is the code to generate the marker and the infowindow.
<script type="text/javascript">
function initialize() {
var myOptions = {
zoom: 3,
center: new google.maps.LatLng(41.850033, -87.6500523),
disableDefaultUI: true,
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
setMarkers(map, offices);
}
/**
* Data for the markers consisting of a name, a LatLng and a zIndex for
* the order in which these markers should display on top of each
* other.
*/
var offices = [<cfoutput>#officeList#</cfoutput>];
function setMarkers(map, locations) {
// Add markers to the map
// Marker sizes are expressed as a Size of X,Y
// where the origin of the image (0,0) is located
// in the top left of the image.
// Origins, anchor positions and coordinates of the marker
// increase in the X direction to the right and in
// the Y direction down.
var image = new google.maps.MarkerImage('images/pin.png',
// This marker is 20 pixels wide by 32 pixels tall.
new google.maps.Size(14, 26),
// The origin for this image is 0,0.
new google.maps.Point(0, 0),
// The anchor for this image is the base of the flagpole at 0,32.
new google.maps.Point(0, 32));
for (var i = 0; i < locations.length; i++) {
var office = locations[i];
var myLatLng = new google.maps.LatLng(office[1], office[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
title: office[0],
zIndex: office[3]
});
var contentString = "Hello!!!";
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
}
</script>
I've also stumbled across this problem.
Here's how I fixed it:
I used a function to bind a marker to an infowindow.
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
title: office[0],
zIndex: office[3]
});
var contentString = "Hello!!!";
var infowindow = new google.maps.InfoWindow;
bindInfoW(marker, contentString, infowindow);
}
function bindInfoW(marker, contentString, infowindow)
{
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
}
http://www.codefx.biz/2011/01/google-maps-api-v3-multiple-infowindows
this way also works!
Related
I have this code that allows users to insert pins in Google Maps, by clicking on the map. Now I'm trying to make this pin draggable, so I just added draggable:true, in the initialization of the markers. But this is not updating the field with the coordinates. It only works if the user clicks in another place. What am I missing?
// global "map" variable
var map = null;
var marker = null;
// popup window for pin, if in use
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150,50)
});
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
google.maps.event.trigger(marker, 'click');
return marker;
}
function initialize() {
// the location of the initial pin
var myLatlng = new google.maps.LatLng(-19.919131, -43.938637);
// create the map
var myOptions = {
zoom: 15,
center: myLatlng,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// establish the initial marker/pin
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Property Location",
draggable:true,
icon: {
url: 'https://4.bp.blogspot.com/-nHydF9OdHLw/V8OxZbpJW6I/AAAAAAAAADM/G_QLEm7aScUOc3XwZmc5X8DmMHp7FK3RwCLcB/s1600/BikeSpot-Pin-Logo.png',
// base image is 60x60 px
size: new google.maps.Size(64, 96),
// we want to render # 30x30 logical px (#2x dppx or 'Retina')
scaledSize: new google.maps.Size(32, 48),
// the most top-left point of your marker in the sprite
// (based on scaledSize, not original)
origin: new google.maps.Point(0, 0),
// the "pointer"/anchor coordinates of the marker (again based on scaledSize)
anchor: new google.maps.Point(16, 48)
}
});
// establish the initial div form fields
formlat = myLatlng.lat();
formlng = myLatlng.lng();
document.getElementById("LatLng-Input").value = myLatlng.toUrlValue();
// close popup window
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// removing old markers/pins
google.maps.event.addListener(map, 'click', function(event) {
//call function to create marker
if (marker) {
marker.setMap(null);
marker = null;
}
// Information for popup window if you so chose to have one
/*
marker = createMarker(event.latLng, "name", "<b>Location</b><br>"+event.latLng);
*/
var image = 'https://4.bp.blogspot.com/-nHydF9OdHLw/V8OxZbpJW6I/AAAAAAAAADM/G_QLEm7aScUOc3XwZmc5X8DmMHp7FK3RwCLcB/s1600/BikeSpot-Pin-Logo.png';
var myLatLng = event.latLng ;
/*
var marker = new google.maps.Marker({
by removing the 'var' subsquent pin placement removes the old pin icon
*/
marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
title:"Bicicletario",
icon: {
url: 'https://4.bp.blogspot.com/-nHydF9OdHLw/V8OxZbpJW6I/AAAAAAAAADM/G_QLEm7aScUOc3XwZmc5X8DmMHp7FK3RwCLcB/s1600/BikeSpot-Pin-Logo.png',
// base image is 60x60 px
size: new google.maps.Size(64, 96),
// we want to render # 30x30 logical px (#2x dppx or 'Retina')
scaledSize: new google.maps.Size(32, 48),
// the most top-left point of your marker in the sprite
// (based on scaledSize, not original)
origin: new google.maps.Point(0, 0),
// the "pointer"/anchor coordinates of the marker (again based on scaledSize)
anchor: new google.maps.Point(16, 48)
}
});
// populate the form fields with lat & lng
formlat = event.latLng.lat();
formlng = event.latLng.lng();
document.getElementById("LatLng-Input").value = formlat +", "+formlng
});
}
});
}
The HTML with the input I'm receiving the coordinates is:
<div id='map_canvas'/>
<input id='LatLng-Input' size='20' type='text'/>
It's not updating the coordinates because you don't tell it to do so. You have to add a dragend-handler and update your element, where you display the coordinates when the drag of the marker is finished:
marker.addListener('dragend', function(event){
document.getElementById("LatLng-Input").value = event.latLng.lat() + ", " + event.latLng.lng();
});
If you would have an infowindow you would have to update the content of the infowindow:
marker.addListener('dragend', function(event){
infoWindow.setContent(event.latLng.lat() + ", " + event.latLng.lng());
});
If you want to update the coordinates also while dragging, add another handler with 'drag' instead of 'dragend'.
The zoom is set to 8 and I am using a KmlLayer for a radius. No matter what I change the zoom setting to the zoom level stays the same on the website: http://mainelyknowleslobster.com/delivery/.
<script>
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
//center: {lat: 28.53687, lng: -81.38328},
center: {lat: 28.5893244, lng: -81.3744571},
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
//Add marker and popup info
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h4 id="firstHeading" class="firstHeading">MAINEly Knowles Lobster</h4>'+
'<div id="bodyContent">'+
'<p><center>887 Jackson Ave<br> Winter Park, FL 32789<br> Phone: 407-960-7441<br> Contact Us!</center></p>'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: {lat: 28.5893244, lng: -81.3744571},
map: map,
title: 'MAINEly Knowles Lobster'
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
// Polygon
var ctaLayer = new google.maps.KmlLayer({
url: 'http://mainelyknowleslobster.com/map/circle.kml',
map: map
});
var markers = [];
// [START region_getplaces]
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
// [END region_getplaces]
}
</script>
I read somewhere that it might have something to do with the perspective of the viewport. I added the preserveViewport property but this did not solve the problem. I wonder if the KML layer has anything to do with it:
directionsDisplay = new google.maps.DirectionsRenderer({
preserveViewport: true
});
You need to set preserveViewport: true for the KmlLayer
// Polygon
var ctaLayer = new google.maps.KmlLayer({
url: 'http://mainelyknowleslobster.com/map/circle.kml',
preserveViewport: true,
map: map
});
proof of concept fiddle
I would like to center my Google Map based on dynamically loaded markers. I have seen the use of 'bounds' and tried to implement Fit to bounds, but I haven't been able to apply it correctly to my map. Here is the code:
var MapStart = new google.maps.LatLng(41.664723,-91.534548);
var markers;
var map;
var infowindow = new google.maps.InfoWindow({maxWidth: 650});
function initialize() {
markers = new Array();
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: MapStart
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
$("#map_list ul li").each(function(index) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng($(this).children(".marker_long").text(), $(this).children(".marker_lat").text()),
map: map,
animation: google.maps.Animation.DROP,
title : $(this).children(".marker_title").text(),
brief: $("div.infoWindow", this).html()
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(marker.brief);
infowindow.open(map, marker);
});
markers.push(marker);
});
}
This is easy, in your initialize method create a bounds object, and then extend the bounds object with each marker's position. Finally, call map.fitBounds() on your map object to center and fit your map to your markers:
function initialize() {
...
var bounds = new google.maps.LatLngBounds();
...
$("#map_list ul li").each(function(index) {
...
//extend the bounds to include each marker's position
bounds.extend(marker.position);
...
});
...
//now fit the map to the newly inclusive bounds
map.fitBounds(bounds);
...
}
//(optional) restore the zoom level after the map is done scaling
var listener = google.maps.event.addListener(map, "idle", function () {
map.setZoom(15);
google.maps.event.removeListener(listener);
});
I want to add, for each of my markers, an event on click to center on this one. I use the lib "MarkerWithLabel" and when I click on a marker, the map is zooming on the last marker each time.
Here is my code :
var map = new google.maps.Map(document.getElementById('map-canvas')),
bounds = new google.maps.LatLngBounds(),
marker = [],
grafxUrl = $('#map-canvas').data('grafx'),
image = {
url : grafxUrl + 'universal/icons/pin_locator.png',
size: new google.maps.Size(24, 31),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(12, 31)
};
for (var i = 0; i < response.length; i++) {
marker = new MarkerWithLabel({
position: new google.maps.LatLng(response[i].fLatitude, response[i].fLongitude),
map: map,
icon : image ,
title : (i+1)+' '+response[i].sName,
labelContent: (i+1),
labelAnchor: new google.maps.Point(3, 25),
labelClass: "markerNum", // the CSS class for the label
});
google.maps.event.addListener(marker, 'click', function() {
map.setZoom(15);
map.setCenter(marker.position);
});
bounds.extend(marker.position);
//now fit the map to the newly inclusive bounds
map.fitBounds(bounds);
}
What is wrong with my script ?
Thanks a lot.
Here is a complete example on how to extend a bounds object to display all markers on the map.
function initialize() {
var southWest = new google.maps.LatLng(40.744656, -74.005966);
var northEast = new google.maps.LatLng(34.052234, -118.243685);
var lngSpan = northEast.lng() - southWest.lng();
var latSpan = northEast.lat() - southWest.lat();
var map = new google.maps.Map(document.getElementById("map-canvas"), {
zoom: 12,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Create the bounds object
var bounds = new google.maps.LatLngBounds();
// Create random markers
for (var i = 0; i < 100; i++) {
// Calculate a random position
var position = new google.maps.LatLng(southWest.lat() + latSpan * Math.random(), southWest.lng() + lngSpan * Math.random());
var marker = new google.maps.Marker({
position: position,
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
map.setZoom(5);
map.setCenter(marker.position);
}
})(marker, i));
// Extend the bounds with the last marker position
bounds.extend(position);
}
// Fit map to the extended bounds
map.fitBounds(bounds);
}
initialize();
This creates 100 random markers within the defined bounds (southWest / northEast coords) then extends a bounds object and finally fit the map to this bounds object. See how the marker variable is defined (within the for loop) and how the fitBounds() is called (outside the for loop). The same should apply to your code.
Below is a working demo. Hope this helps!
JSFiddle demo
var icon = {
url: pointer.png,
size: new google.maps.Size(48,48),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(24,24)
};
var marker = new google.maps.Marker({
position: pos,
map: map,
icon: icon
});
Is it possible to add second image to the marker? I'd like to have double marker for same point, 1 overlaid on top of the other.
I want to have little flag of country next to marker.
Possible?
Prior to the API v3.14, you hack this with a icon and a shadow image file together on the same marker.
Here's how I would solve it with v3.14+
function initialize() {
google.maps.visualRefresh = true;
var mapDiv = document.getElementById('map-canvas');
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(0, 0),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(0, 0),
map: map
});
// CREDIT: https://developers.google.com/maps/documentation/javascript/markers
marker.flag = new google.maps.Marker({
icon: {
url: 'https://google-developers.appspot.com/maps/documentation/javascript/examples/full/images/beachflag.png',
anchor: new google.maps.Point(32, 32)
}
});
marker.flag.bindTo('position', marker);
marker.flag.bindTo('map', marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
See: http://jsfiddle.net/stevejansen/J5swt/