This question already has answers here:
Google Maps JS API v3 - Simple Multiple Marker Example
(15 answers)
Closed 8 years ago.
Like many other people I'm finding identical values within my info windows. Alas, I've been using other posts in an attempt to troubleshoot. No luck.
Issue: Each of my infowindows shows the same values. Sigh.
Any help would be appreciated.
var map;
function initialize() {
var markers = [];
var mapOptions = {
zoom: 4,
scrollwheel: false,
streetViewControl: true,
panControl: true,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
// position: google.maps.ControlPosition.LEFT_CENTER
},
center: new google.maps.LatLng(-25.898854, 134.091377)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
setMarkers(map, beaches);
infowindow = new google.maps.InfoWindow({
content: "Loading..."
});
var input = /** #type {HTMLInputElement} */(
document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(
/** #type {HTMLInputElement} */(input));
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
//url: 'assets/img/icon_pin.png',
//size: new google.maps.Size(40, 52),
//origin: new google.maps.Point(0, 0),
//anchor: new google.maps.Point(26, 20)
};
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
var beaches = [
['Auburn', -33.847113, 151.04485, 1, '100', 'Parramatta', 'Road', 'Auburn', 'NSW', '2144', '02 7837 9800', '06:00 - 22:00', '06:00 - 22:00'],
['Balgowlah Platinum', -33.79284, 151.26376, 2, 'Shop 67, 197-215', 'Condamine', 'Street', 'Balgowlah', 'NSW', '2093', '1300 55 77 99', '06:00 - 21:30', '06:00 - 21:30'],
['Bankstown', -33.931208, 151.02895, 3, 'Unit 1-2, 9', 'Chapel', 'Street', 'South Bankstown', 'NSW', '2200', '02 8707 4700', '06:00 - 22:00', '06:00 - 22:00']
['Bayside', -37.954768, 145.03128, 4, '241 - 245', 'Bay', 'Road', 'Highett', 'VIC', '3190', '03 9559 7400', '06:00 - 22:00', '06:00 - 22:00']
];
function setMarkers(map, locations) {
var image = {
url: 'assets/img/icon_pin.png',
size: new google.maps.Size(40, 52),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(26, 20)
};
var shape = {
coord: [1, 1, 1, 52, 40, 52, 40 , 1],
type: 'poly'
};
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
shape: shape
});
var contentString = '<div class="siteNotice"><h4>'+beach[0]+'</h4><p>'+beach[4]+' '+beach[5]+' '+beach[6]+' '+beach[7]+', '+beach[8]+', '+beach[9]+'</p><p><strong>Contact:</strong> '+beach[10]+'</p><p><strong>Opening Hours:</strong><br><span>Monday:</span> '+beach[11]+'<br><span>Tuesday:</span> '+beach[11]+'<br><span>Wednesday:</span> '+beach[11]+'<br><span>Thursday</span>: '+beach[11]+'<br><span>Friday:</span> '+beach[11]+'<br><span>Saturday</span>: '+beach[11]+'<br><span>Sunday:</span> '+beach[11]+'</p></div>';
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(contentString);
infowindow.open(map, this);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
I had to create an array of info markers to hold the data.
var markers = [];
function addMapLocation(map, lat, long, title, message) {
var locationLatLong = new google.maps.LatLng(lat, long);
var locationMarker = new google.maps.Marker({ position: locationLatLong, map: map, title: title.trim() });
attachMessage(locationMarker, message);
markers.push(locationMarker);
}
function attachMessage(marker, message) {
var locationInfo = new google.maps.InfoWindow({ content: message });
google.maps.event.addListener(marker, 'click', function () { locationInfo.open(marker.get('map'), marker); });
}
Related
Please click here for screen shot I have Google map which shows the relation between locations based on a condition. What I need is to draw lines from one marker to all other markers and open info windows of each marker for marker click. Can anybody suggest the way to perform the task?
var Markerss = {};
var linearray = [];
function initialize() {
var markers = [{ 'lat': '32.803', 'lon': '-96.7699', 'ExpertsCount': 2, 'Type': 'ofsite' }, { 'lat': '44.9542', 'lon': '-93.1139', 'ExpertsCount': 3, 'Type': 'onsite' }, { 'lat': '32.903', 'lon': '-150.0011', 'ExpertsCount': 5, 'Type': 'offsite' }, { 'lat': '61.85', 'lon': '-97.6501', 'ExpertsCount': 9, 'Type': 'onnsite' }];
var mapProp = {
center: new google.maps.LatLng(28.067768, 2.150065),
zoom: 5,
mapTypeId: 'terrain'
};
//var infowindow = new google.maps.InfoWindow({
// content: "Hello World!"
//});
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var icon = "";
for (i = 0; i <= markers.length; i++) {
var data = markers[i];
var myLatlng = new google.maps.LatLng(parseFloat(data.lat), parseFloat(data.lon));
if (data.Type == "offsite") {
icon = 'http://maps.google.com/mapfiles/ms/icons/green-dot.png';
}
else if (data.Type == "onsite") {
icon = 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png';
}
else {
icon = 'http://maps.google.com/mapfiles/ms/icons/red-dot.png';
}
var div = document.createElement('DIV');
div.innerHTML = '<div class="mapicon" id="dvIcon" style="background-image: url(images/mapiconsmall.png);" onmouseover="javascript:$(this).next().show()" onmouseout="javascript:$(this).next().hide()" ><div class="maindiv"style="width:24px;margin-top:3px; text-align:center;margin-left:1px;"><span style="font-weight:bolder;font-size:11px;"> ' + data.ExpertsCount + '</span></div></div><div id="dvExpName" style="display:none;z-index:1;position:absolute;">' + data.expName + '</div>';
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: i,
content: div,
flat: true,
anchor: RichMarkerPosition.MIDDLE,
icon: icon
});
Markerss[i] = marker;
//if (data.Type == "onsite") {
// Marker[i].setClickable = false;
//}
//else {
// Marker[i].setClickable = true;
//}
// Attaching a click event to the current marker
if (markers[i].Type != "onsite") {
google.maps.event.addListener(marker, 'click', function (event) {
if (linearray.length != 0)
{
for (i = 0; i < linearray.length; i++) {
linearray[i].setMap(null);
}
}
var lineSymbol = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
scale: 3,
strokeColor: 'red'
};
for (j = 0; j < markers.length; j++) {
var marker = markers[j];
var lat = parseFloat(markers[j].lat);
var lon = parseFloat(markers[j].lon);
if (lat != event.latLng.lat()) {
var line = new google.maps.Polyline({
path: [{ lat: event.latLng.lat(), lng: event.latLng.lng() }, { lat: lat, lng: lon }],
icons: [{
icon: lineSymbol,
offset: '100%'
}],
strokeColor: 'red',
map: map
});
linearray.push(line);
}
var infoWindow = new google.maps.InfoWindow({
content: '<b><i>Expert Count:</i></b> <span>' + parseInt(markers[j].ExpertsCount) + '</span><br/><b><i>Expert Count:</i></b> <span>' + parseInt(markers[j].ExpertsCount) + '</span><br/>'
});
infoWindow.open(map, Markerss[j]);
}
});
}
}
}
I've been stuck on this issue for a while now and could really use some help. In a Google Map, I have a list of markers which are being treated as a markerArray, with their own custom icons. But along with displaying those markers, I would like for it to create a marker which is placed at the users geotagged location. I have tried merging the suggestions I've come across here on stack overflow, and have successfully gotten the users browser to center the map based off of geolocation, but whenever I try to add a marker outside of the standard var=locations, all of the markers disappear. I am providing my working code, which simply lacks the feature to add the "current location" marker. If anyone has any input, I'd be thrilled.
var map = null;
var markerArray = [];
function initialize() {
var myOptions = {
zoom: 13,
center: new google.maps.LatLng(40.746613, -73.990109),
mapTypeControl: false,
navigationControl: false,
streetViewControl: false,
zoomControl: false,
styles: [{featureType:"landscape",stylers:[{saturation:-100},{lightness:65},{visibility:"on"}]},{featureType:"poi",stylers:[{saturation:-100},{lightness:51},{visibility:"simplified"}]},{featureType:"road.highway",stylers:[{saturation:-100},{visibility:"simplified"}]},{featureType:"road.arterial",stylers:[{saturation:-100},{lightness:30},{visibility:"on"}]},{featureType:"road.local",stylers:[{saturation:-100},{lightness:40},{visibility:"on"}]},{featureType:"transit",stylers:[{saturation:-100},{visibility:"simplified"}]},{featureType:"administrative.province",stylers:[{visibility:"off"}]/**/},{featureType:"administrative.locality",stylers:[{visibility:"off"}]},{featureType:"administrative.neighborhood",stylers:[{visibility:"on"}]/**/},{featureType:"water",elementType:"labels",stylers:[{visibility:"on"},{lightness:-25},{saturation:-100}]},{featureType:"water",elementType:"geometry",stylers:[{hue:"#ffff00"},{lightness:-25},{saturation:-97}]}]
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
});
}
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
var locations = [
['90 West Apartment', 40.709943, -74.014430, 7, 'images/pin2.png'],
['Caffe Vita', 40.719652, -73.988411, 6, 'images/pin1.png'],
['Croxleys Ale House', 40.722480, -73.983386, 5, 'images/pin1.png'],
['Grays Papaya', 40.778291, -73.981829, 4, 'images/pin2.png'],
['The Back Room', 40.718723, -73.986913, 3, 'images/pin1.png'],
['MUD Coffee', 40.729912, -73.990678, 2, 'images/pin1.png'],
['Nurse Bettie', 40.718820, -73.986863, 1, 'pin2.png']];
for (var i = 0; i < locations.length; i++) {
createMarker(new google.maps.LatLng(locations[i][1], locations[i][2]),locations[i][0], locations[i][3], locations[i][4]);
}
mc.addMarkers(markerArray, true);
}
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
function createMarker(latlng, myTitle, myNum, myIcon) {
var contentString = myTitle;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: myIcon,
zIndex: Math.round(latlng.lat() * -100000) << 5,
title: myTitle
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
markerArray.push(marker);
}
window.onload = initialize;
Let's try this.
Put this in your initialize(): navigator.geolocation.getCurrentPosition(showPosition);
Then define showPosition:
var showPosition = function (position) {
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Do whatever you want with userLatLng.
var marker = new google.maps.Marker({
position: userLatLng,
title: 'Your Location',
map: map
});
}
I use this code on my site.
It show map with markers and when you tap on marker you go to another page.
And you see title when you put cursor on marker, i need that title always been shown.
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript">
var points = [
["Page 1", 55.771683, 37.571274, 1, 'link to page 1'],
["Page 2", 55.7636, 37.606, 1, 'link to page 1']
];
function setMarkers(map, locations) {
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
for (var i = 0; i < locations.length; i++) {
var flag = new google.maps.MarkerImage(
'http://googlemaps.googlermania.com/google_maps_api_v3/en/Google_Maps_Marker.png',
new google.maps.Size(37, 34),
new google.maps.Point(0,0),
new google.maps.Point(0, 19)
);
var place = locations[i];
var myLatLng = new google.maps.LatLng(place[1], place[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: flag,
shape: shape,
title: place[0],
zIndex: place[3],
url: place[4]
});
google.maps.event.addListener(marker, 'click', function() {
// alert('go to ' + this.url); //
window.location.href = this.url;
});
}
}
function initialize() {
var myOptions = {
center: new google.maps.LatLng(55.766731,37.6010157,14),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
setMarkers(map, points);
}
</script>
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', initialize);
</script>
My question is i need that title -> (title: place[0]) allways show.
Now, when i use my code i see title just when i move cursor on marker.
Unfortunately I was not able to find any code / example how to draw great circle distance *between three(3) points on google maps*??
Here is the javascript for two points. How can I make it work with three points?
var geocoder;
var map;
var addresses;
var results;
var dist;
function initialize() {
geocoder = new google.maps.Geocoder();
address1 = document.getElementById("distancefrom").value;
address2 = document.getElementById("distanceto").value;
(distance(address1, address2));
}
function distance(add1, add2) {
if (!geocoder)
return 'Error, no geocoder';
addresses = new Array(2);
addresses[0] = add1;
addresses[1] = add2;
results = new Array(2);
results[0] = new Array(2);
results[1] = new Array(2);
results[0][0] = 0; results[0][1] = 0; results[1][0] = 0; results[1][1] = 0.87;
geocoded(1);
}
function geocoded(i) {
geocoder.geocode( { 'address': addresses[i] }, function(res, status) {
if (status == google.maps.GeocoderStatus.OK) {
results[i][0] = parseFloat(res[0].geometry.location.lat());
results[i][1] = parseFloat(res[0].geometry.location.lng());
i--;
if (i >= 0)
geocoded(i);
else {
var latlng1 = new google.maps.LatLng(results[0][0], results[0][1]);
var latlng2 = new google.maps.LatLng(results[1][0], results[1][1]);
dist = google.maps.geometry.spherical.computeDistanceBetween(latlng1, latlng2)/1000;
var dmi = 0.539957*dist;
document.getElementById('totaldistancemiles').value = dmi.toFixed(2);
document.getElementById('totaldistancekm').value = dist.toFixed(2);
showMap(latlng1,latlng2);
}
}
});
}
function showMap(location1,location2) {
latlng = new google.maps.LatLng((location1.lat()+location2.lat())/2,
(location1.lng()+location2.lng())/2);
faddress1 = document.getElementById("distancefrom").value;
faddress2 = document.getElementById("distanceto").value;
var mapOptions =
{
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
var flightPlanCoordinates = [
location1,
location2
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: .5,
geodesic: true,
strokeWeight: 3
});
flightPath.setMap(map);
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#000000",
strokeOpacity: .5,
strokeWeight: 0
});
flightPath.setMap(map);
var igreen= 'https://dl.dropboxusercontent.com/u/85343999/igreen.gif';
var marker = new google.maps.Marker({
map: map,
icon: igreen,
position: location1
});
var latlngbounds;
latlngbounds = new google.maps.LatLngBounds();
latlngbounds.extend( location1);
latlngbounds.extend( location2);
map.fitBounds(latlngbounds);
var infowindow = new google.maps.InfoWindow();
infowindow.setContent(faddress1);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
var marker2 = new google.maps.Marker({
map: map,
icon: igreen,
position: location2
});
var infowindow2 = new google.maps.InfoWindow();
infowindow2.setContent(faddress2);
google.maps.event.addListener(marker2, 'click', function() {
infowindow2.open(map, marker2);
});
}
The following code uses Googles geometry library to calculate distances between points.The locations are stored in this case in an array, but can be obtained from textboxes etc. The distances are given in metres .
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>
<script type="text/javascript">
var coords = [
[35.733972, -5.881999],
[35.734077, -5.881033],
[35.736898, -5.877771],
];
function calcDistance() {
var first = new google.maps.LatLng(coords[0][0],coords[0][1]);
var second = new google.maps.LatLng(coords[1][0],coords[1][1]);
var third = new google.maps.LatLng(coords[2][0],coords[2][1]);
var distance1 = google.maps.geometry.spherical.computeDistanceBetween(first, second);
var distance2 = google.maps.geometry.spherical.computeDistanceBetween(first, third);
var distance3 = google.maps.geometry.spherical.computeDistanceBetween(second, third);
showDistance(distance1,distance2,distance3);
}
function showDistance(distance1,distance2,distance3) {
document.write("Distance1 "+distance1 + " metres <br>");
document.write("Distance2 "+distance2 + " metres <br>");
document.write("Distance3 "+distance3 + " metres <br>");
}
i use markerclusterer and i show popup info like that: ( in my js file )
var infowindow = new google.maps.InfoWindow();
after that i use :
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(
'<div id="wrapper">'+
'<div id="header">'+data.photos[i].owner_name+':</div>'+
'<div id="content">'+data.photos[i].photo_title+'</div>'+
'</div>'
);
infowindow.open(map, marker);
}
})(marker, i));
in this case i can customize only that information, what i put in my box ( infowindow.setContent )
but how can i customize popup windows ?? if i want some border-radius on my popup...
i saw infobox plugin, but i can't to set it up ( for many popups - in FOR cicle )
$(function(){
function initialize() {
var styles = [[{
url: '../images/conv30.png',
height: 27,
width: 30,
anchor: [3, 0],
textColor: '#ff00ff',
textSize: 10
}, {
url: '../images/conv40.png',
height: 36,
width: 40,
anchor: [6, 0],
textColor: '#ff0000',
textSize: 11
}, {
url: '../images/conv50.png',
width: 50,
height: 45,
anchor: [8, 0],
textSize: 12
}]];
var center = new google.maps.LatLng(37.4419, -122.1419);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions:{
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ANDROID
},
scaleControl: true
});
var infowindow = new google.maps.InfoWindow();
var style = 0;
var mcOptions = {gridSize: 50, maxZoom: 9, styles: styles[style]};
var imageUrl = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&chco=00FF00,FF00FF,000000&ext=.png';
var markerImage = new google.maps.MarkerImage(imageUrl, new google.maps.Size(24, 32));
var markers = [];
for (var i = 0; i < 100; i++) {
var dataPhoto = data.photos[i];
var title = data.photos[i].photo_title;
var latLng = new google.maps.LatLng(dataPhoto.latitude, dataPhoto.longitude);
var marker = new google.maps.Marker({
position: latLng,
title: title,
icon: markerImage
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(
'<div id="wrapper">'+
'<div id="header">'+data.photos[i].owner_name+':</div>'+
'<div id="content">'+data.photos[i].photo_title+'</div>'+
'</div>'
);
infowindow.open(map, marker);
}
})(marker, i));
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers, mcOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
});
i know that i must chang infowindow.setContent, but how...
help my plz with that.