I've been digging around everywhere and I can't seem to figure this out. It's driving me crazy! I'm a newbie to javascript in general, so I can't quite put a finger on the translation that would fix my issue. I noticed that a lot of people have this problem, but they all seem to use more advanced(or just confusing) code than I. Anyway, here goes!
I've been having the problem where all of my markers share the same content.
function initialize() {
var myOptions = {
center: new google.maps.LatLng(34.151271, -118.449537),
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
streetViewControl: false,
panControl: false,
zoomControl: true,
zoomControlOptions: { style: google.maps.ZoomControlStyle.SMALL },
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
setMarkers(map, clubs);
}
var clubs = [
['Poop', 34.223868, -118.601575, 'Dookie'],
['Test Poop', 34.151271, -118.449537, 'Test Business']
];
function setMarkers(map, locations) {
var image = new google.maps.MarkerImage('images/image.png',
new google.maps.Size(25, 32),
new google.maps.Point(0,0),
new google.maps.Point(0, 32)
);
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
for (var i = 0; i < locations.length; i++) {
var club = locations[i];
var myLatLng = new google.maps.LatLng(club[1], club[2]);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
shape: shape,
title: club[0],
});
google.maps.event.addListener(marker, 'click', function(){
infowindow.setContent(club[3]);
infowindow.open(map, this);
});
}
}
I know I'm crappy, but someone please help me! :P
The problem is because you're setting the event listener for the marker click within a loop. So all the markers end up only getting the content for the last of your markers. Try this instead. Create a new global function:
function bindInfoWindow(marker, map, infowindow, html) {
marker.addListener('click', function() {
infowindow.setContent(html);
infowindow.open(map, this);
});
}
Then within your loop, replace this:
google.maps.event.addListener(marker, 'click', function(){
infowindow.setContent(club[3]);
infowindow.open(map, this);
});
with this:
// add an event listener for this marker
bindInfoWindow(marker, map, infowindow, club[3]);
When setting the marker object (var marker = new ...) change this line: "title: club[0]," to "title: club[i],". Yes, just change the 0 to i.
That should solve the problem.
Try this link for a tutorial on Google Maps API with examples.
http://code.google.com/apis/maps/documentation/javascript/tutorial.html
It should be very easy and helpful.
Related
I have the following code that creates a marker on Google Maps:
function initializeMap() {
var lat = '-32.089608'; //Set your latitude.
var lon = '115.933216'; //Set your longitude.
var centerLon = lon - 0.0105;
var myOptions = {
scrollwheel: false,
draggable: false,
disableDefaultUI: true,
center: new google.maps.LatLng(lat, centerLon),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Bind map to elemet with id map-canvas
var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(lat, lon),
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
infowindow.open(map, marker);
}
I would like to add custom text to the pointer above the default marker but I cannot work out how to do it. At the moment it displays a small empty box above the default marker. (I am unable to post an example image due to lack of reputation points.
I am not very experienced with coding so any help is appreciated.
Thank you
You only need add content into your infowindow:
var infowindow = new google.maps.InfoWindow({
content: 'abcxyz'
});
I doubt the standard library supports this.
But you can use the google maps utility library:
https://code.google.com/p/google-maps-utility-library-v3/wiki/Libraries#MarkerWithLabel
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
var marker = new MarkerWithLabel({
position: myLatlng,
map: map,
draggable: true,
raiseOnDrag: true,
labelContent: "A",
labelAnchor: new google.maps.Point(3, 30),
labelClass: "labels", // the CSS class for the label
labelInBackground: false
});
The basics about marker can be found here:
https://developers.google.com/maps/documentation/javascript/overlays#Markers
Google Maps API v3 marker with label
You only need to edit your marker click event function as below.
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
infoWindow.setContent('abcdxyz'); // add this line to your existing code
});
With this you can deal with multiple infoWindow for multiple markers.
Also if you want to display contents on mouseover, then you can use title property of marker like:
var marker = new google.maps.Marker({
position: {lat:lat, lng:lng},
map: map,
title: 'abcXYZ' // this will be displayed on marker mousover
});
I need to allow users to create polylines on a google map and also allow them to delete a node between the polylines they created. The result of this removal should be a new polyline connecting the two new neighboring nodes. At the moment I'm struggling with allowing a user to delete a node. I've researched a bit and found a google reference and this SO question. Unfortunately, both of them assume that I have a reference to the polyline somewhere, which I don't, since the polyline is being created dynamically by the user.
This is the code that I currently use :
function initialize() {
var mapOptions = {
center: { lat: 45.797436, lng: 24.152044 },
zoom: 12
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.MARKER,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.MARKER,
google.maps.drawing.OverlayType.POLYLINE
]
},
markerOptions: {
icon: '/Mvc/Content/Styles/dropDownArrow.png'
},
polylineOptions: {
editable: true,
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'markercomplete', markerCompleted);
google.maps.event.addListener(drawingManager, 'polylinecomplete', polylineCompleted);
function markerCompleted(marker) {
var coordinates = { lng: marker.getPosition().lng(), lat: marker.getPosition().lat() };
alert('The coordinates for the new marker are: lat:' + coordinates.lat + ', long: ' + coordinates.lng);
}
function polylineCompleted(polyline) {
}
}
google.maps.event.addDomListener(window, 'load', initialize);
What I've tried is to map the polyline parameter inside the polylineCompleted event handler to a global variable, and then use the solution found in the SO link to somehow update the polyline, after which, using the getMap() and setMap() functions of the DrawingManager class, to update the map, but I got stuck. Is there any way of allowing a user to delete a polyline node, without having a reference to the polyline object?
Not sure this is what you are trying to achieve, but here is an example on how to let a user add and remove nodes from a polyline without using the drawingManager.
var map, polyline, markers = new Array();
function initialize() {
var mapOptions = {
zoom: 6,
center: new google.maps.LatLng(20.291, 153.027),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
polyline = new google.maps.Polyline({
strokeColor: 'red',
strokeWeight: 1,
map: map
});
google.maps.event.addListener(map, 'click', function (event) {
addPoint(event.latLng);
});
}
function removePoint(marker) {
for (var i = 0; i < markers.length; i++) {
if (markers[i] === marker) {
markers[i].setMap(null);
markers.splice(i, 1);
polyline.getPath().removeAt(i);
}
}
}
function addPoint(latlng) {
var marker = new google.maps.Marker({
position: latlng,
map: map
});
markers.push(marker);
polyline.getPath().setAt(markers.length - 1, latlng);
google.maps.event.addListener(marker, 'click', function (event) {
removePoint(marker);
});
}
initialize();
JSFiddle demo
Click on the map to add a point and click on a marker to remove a point.
I' am using Google Map to plot the marker and a small popup box that will appear when someone clicks on the market. Image is attached. By Default, Google has set fixed width of the Popup and I wanted to change its size. I was not able to anything on Documentation.
Below are my codes
<script type="text/javascript">
function initialize() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(-14.306407, -170.695018),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var voyagePlanCoordinates = [
new google.maps.LatLng(),
];
var voyagePath<?php echo $voyage_id; ?> = new google.maps.Polyline({
path: voyagePlanCoordinates,
geodesic: true,
strokeColor: "",
strokeOpacity: 1.0,
strokeWeight: 5
});
voyagePath.setMap(map);
setMarkers(map, voyages);
}
var voyages = [];
function setMarkers(map, locations) {
var image = {
url: '/wp-content/themes/theme/resources/images/marker.png',
size: new google.maps.Size(20, 32),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(0, 32)
};
for (var i = 0; i < locations.length; i++) {
var voyage = locations[i];
var myLatLng = new google.maps.LatLng(voyage[1], voyage[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
title: voyage[0],
zIndex: voyage[3]
});
voyage_msg(marker, i);
}
}
function voyage_msg(marker, num){
var message = [];
var infowindow = new google.maps.InfoWindow({
content: message[num]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(marker.get('map'), marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Please Help!
You don't need any extra code or api call to set the width of the popover. All you need is basic CSS
.map-closures{
width: 200px;
}
That should do the trick.
I have three arrays : myLats, (latitudes) myLngs (longitudes) and myLocs (address strings)
e.g. myLats[0] = 53.3534751, ,myLngs[0] = -2.5682085, myLocs[0] = Longwood Rd Appleton Warrington. So the elements of each array all correspond to each other numerically.
When constructing the map in my initialize() function, I loop through these to place multiple markers at the correct coordinates, and i'm also trying to have each marker having an infowindow appear when clicked, yet when i click a marker an infowindow simply does not appear. Any help with this would be greatly appreciated.
Code:
function initialize() {
var myOptions = {
center: new google.maps.LatLng(54.00366, -2.547855),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
var marker, infowindow, i;
for (i = 0; i <= myLats.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(myLats[i], myLngs[i]),
map: map,
clickable: true,
icon: '". url::base() ."resources/icons/accident.png',
});
infowindow = new google.maps.InfoWindow({
content: myLocs[i],
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
}
}
That's a common problem when dealing with more than one marker. You aren't in fact creating a new window for each marker but must redefining the single window for each marker.
You'll find the problem and solution on page 88 onwards of Google Map API V3
If you are new to Google Maps API, I would recommend reading that book, it gave me a great start and I avoided a lot of the "common" mistakes.
Hope this helps.
Jim
I made a few changes, like adding the markers inside a function, adding 'var', and changing i <= myLats.length to i < myLats.length. It was a combination of these changes that made it work.
var myLats = [ 54.20366, 54.42366, 54.64366];
var myLngs = [ -2.54788, -2.66788, -2.78788];
var myLocs = [ "Loc a" , "Loc b" , "Loc c"];
function initialize()
{
var myOptions =
{
center: new google.maps.LatLng(54.00366,-2.547855),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),myOptions);
var marker, infowindow, i;
for (i=0; i < myLats.length; i++)
{
addMarker(i);
}
function addMarker(i) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(myLats[i],myLngs[i]),
map: map,
clickable: true,
//icon: '". url::base() ."resources/icons/accident.png',
});
var infowindow = new google.maps.InfoWindow({
content: myLocs[i]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
}
However, I'm guessing you want a solution that keeps only one infowindow open, I had this figured out first:
var myLats = [ 54.20366, 54.42366, 54.64366];
var myLngs = [ -2.54788, -2.66788, -2.78788];
var myLocs = [ "Loc a" , "Loc b" , "Loc c"];
var map, marker, infowindow, i;
function initialize()
{
var myOptions =
{
center: new google.maps.LatLng(54.00366,-2.547855),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),myOptions);
infowindow = new google.maps.InfoWindow({ });
for (i = 0; i < myLats.length; i++) {
addMarker(i);
}
}
function addMarker(i) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(myLats[i],myLngs[i]),
map: map,
clickable: true
//icon: '". url::base() ."resources/icons/accident.png'
});
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(myLocs[i]);
infowindow.open(map,marker);
});
}
I am using google map api v3 with js and I am trying to to open infowndow on each marker on the map but through my code it is not opening here is my code sample please check it and tell me where is the error
<script type="text/javascript">
var map;
var markers = new Array();
function initialize() {
var map_center = new google.maps.LatLng(31.2330555556,72.3330555556);
var GPS = <%=GPS %>
var myOptions = {
zoom: 8,
scaleControl:true,
pancontrol: true,
streetViewControl: true,
center: map_center,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
mapTypeId: google.maps.MapTypeId.HYBRID
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var infowindow = new google.maps.InfoWindow();
for(i=0; i<GPS.length; i++)
{
var image = 'ico/no.png';
var ContentString = GPS[i].TITLE;
markers[i] = new google.maps.Marker(
{
position: GPS[i].GPS,
map: map,
draggable:true,
icon:image,
title:GPS[i].TITLE
});
google.maps.event.addListener(markers[i], 'click', function() {
infowindow.setContent(ContentString);
infowindow.open(map,markers[i]);
});
}
}
</script>
Try the following code:
google.maps.event.addListener(markers[i], 'click', function() {
infowindow.setContent(ContentString);
infowindow.open(map,this);
});
I have completed a program recently using the same api as yours. Facing to the same problem,I found the key factor is that the function of addlistener would work after the loop ended.It is said that the variable 'i' has reach to the maximizing value when the function of addlistener worked.So I have added a few steps to handle the problem. You can have a look at mine and I hope it is helpful for you.
function ShowParkingPoints() {
var adNum=document.getElementById("tableOne").rows.length;
var i;
var j;
var l;
var ly;
for (i=1;i<adNum;i++)
{
for(j=1;j<5;j++)
{
var k=i-1;
addArray[k]+=document.getElementById("tableOne").rows[i].cells[j].innerHTML;
}
}
for (i=0;i<adNum-1;i++){
var image = new sogou.maps.MarkerImage('images/flag.png',
new sogou.maps.Size(60, 60),
new sogou.maps.Point(0,0),
new sogou.maps.Point(0, 60));
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
geocoder.geocode( { 'address': addArray[i]}, function(results, status) {
if (status == sogou.maps.GeocoderStatus.OK) {
var str=results[0].formatted_address;
//infowindow.setContent(str);
var marker1= new sogou.maps.Marker({
map: map,
icon: image,
shape: shape,
draggable:true,
position: results[0].geometry.location
});
i=i-1
markerArrayS[i]=marker1;
locationArray[i]=results[0].geometry.location;
sogou.maps.event.addListener(markerArrayS[i], 'click', function(event) {
makerClicked(event.latLng);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
map.setCenter(mapCenter);
map.setZoom(13);
}
I think you just need to use 'i=i-1' to replace 'i' when you start to login event watcher.You can have a try. In a way,you need to notice that the order you storage in arrays when you want to read them out.