javascript - Add text to gmap marker - google-maps

I use gmap for geolocation, i.e. to set markers on a google map on specific positions.
Now what I want to achieve is to set markers and as soon as a user clicks on one of these markers, a info window opens and shows specific text. Every marker has its own text.
Now the problem is that I can't determine which marker the user has clicked and therefore can't set the right text.
Here's a code snippet:
//**Global variables**/
var thingsOfInterest = new Array(new Array(), new Array(),new Array());
var map = null;
//End Global variables
//init google map
function initGoogleMaps(){
map = new google.maps.Map(document.getElementById("map_canvas"));
var centerMap = new google.maps.LatLng(48.337881,14.320323);
$('#map_canvas').gmap({'zoom':7,'center': centerMap});
$('#map_canvas').gmap('option', 'zoom', 10);
//This is not working on my ios-simulator, no idea why. Anyway....
forge.geolocation.getCurrentPosition(function(position) {
alert("Your current position is: "+position);
}, function(error) {
});
}
/*End init map*/
/*Set the markers on the map*/
function setMarkers() {
/* thingsOf Interest contains:
* thingsOfInterest[i][0] -> the text that the marker should hold
* thingsOfInterest[i][1] -> the latitude
* thingsOfInterest[i][2] -> the longitude
*/
for (var i = 0; i < thingsOfInterest.length; i++) { //Iterate through all things
var item = thingsOfInterest[i]; //get thing out of array
var itemLatLng = new google.maps.LatLng(item[1], item[2]);
$('#map_canvas').gmap('addMarker', {'position': new google.maps.LatLng(item[1],item[2]) } ).click(function(e) {
$('#map_canvas').gmap('openInfoWindow', {'content': 'dummyContent'}, this); ///////SET REAL CONTENT HERE
});
}
}
Now this works all great, but what I miss is to get the marker the user has clicked on in the function()-eventHandler. If I could get the specific marker, I could set the text on it.
I hope this is clear enough.
Any help is very appreciated.
Thanks,
enne

Assuming your code with dummy text is working, you can pass your text right away..
$('#map_canvas').gmap('addMarker', {'position': new google.maps.LatLng(item[1],item[2])})
.click(function(e) {
$('#map_canvas').gmap('openInfoWindow', {'content': item[0]}, this);
});
Or another approach would be:
function setMarkers() {
for (var i = 0; i < thingsOfInterest.length; i++) {
var item = thingsOfInterest[i];
var itemLatLng = new google.maps.LatLng(item[1], item[2]);
var marker = new google.maps.Marker({ position: itemLatLng, map: map });
google.maps.event.addListener(marker, 'click', function () {
var infowindow = new google.maps.InfoWindow({ content: item[0] });
infowindow.open(map, marker);
});
}
}

Related

Google maps Spiderfier, map unresponsive after setmap(null)

I have a function that loads my map to keep my map static.
<script>
var delArray = new Array();
var gm;
var map;
var iw;
var oms;
window.onload = function(){
gm = google.maps;
map = new gm.Map(document.getElementById('map_canvas'), {
mapTypeId: gm.MapTypeId.TERRAIN,
center: new gm.LatLng(-29.335205, 24.793563),
scrollwheel: false,
zoom: 6
});
iw = new gm.InfoWindow();
oms = new OverlappingMarkerSpiderfier(map,
{markersWontMove: true, markersWontHide: true});
}
</script>
I then use another function to construct my spiderfier data.
<script>
function spider(mapData){
var usualColor = 'eebb22';
var spiderfiedColor = 'ffee22';
var iconWithColor = function(color) {
return 'http://chart.googleapis.com/chart?chst=d_map_xpin_letter&chld=pin|+|' +
color + '|000000|ffff00';
}
var shadow = new gm.MarkerImage(
'https://www.google.com/intl/en_ALL/mapfiles/shadow50.png',
new gm.Size(37, 34), // size - for sprite clipping
new gm.Point(0, 0), // origin - ditto
new gm.Point(10, 34) // anchor - where to meet map location
);
oms.addListener('click', function(marker) {
iw.setContent(marker.desc);
iw.open(map, marker);
});
oms.addListener('spiderfy', function(markers) {
for(var i = 0; i < markers.length; i ++) {
markers[i].setIcon(iconWithColor(spiderfiedColor));
markers[i].setShadow(null);
}
iw.close();
});
oms.addListener('unspiderfy', function(markers) {
for(var i = 0; i < markers.length; i ++) {
markers[i].setIcon(iconWithColor(usualColor));
markers[i].setShadow(shadow);
}
});
var bounds = new gm.LatLngBounds();
for (var i = 0; i < mapData.length; i ++) {
var datum = mapData[i];
var loc = new gm.LatLng(datum[0], datum[1]);
bounds.extend(loc);
var marker = new gm.Marker({
position: loc,
title: datum[2],
animation: google.maps.Animation.DROP,
map: map,
icon: iconWithColor(usualColor),
shadow: shadow
});
marker.desc = datum[3];
oms.addMarker(marker);
delArray.push(marker);
}
map.fitBounds(bounds);
// for debugging/exploratory use in console
window.map = map;
window.oms = oms;
}
</script>
And Another to remove markers from the map:
<script>
function delMe(){
if(delArray){
for(i =0; i <= delArray.length; i++){
delArray[i].setMap(null);
}
this.delArray = new Array();
}
}
</script>
My map data (mapData) comes from a php script and passed on via Jason. And that's also where I call my delete function right before I call my spider (map) function. This I do to clear the map before I pass the new data.
$( document ).ready(function() {
delMe();
var pdata = $js_array;
spider(pdata);
});
Now, my problem is that all data is displaying perfectly but after calling the delMe() function it clears the markers 100% but then my map become unresponsive it's not loading new data when calling the spider() function with new data.
I can overcome this problem by reloading/creating the map again, but I want to avoid that and only use a static map. And if I don't delete markers it just fill the map with 100's of markers mixing the old and new.
I am a bit of a noob when it comes to javascript/jquery, any help will be much appreciated!.
It looks like you're missing an OMS removeMarker call in your delMe function, which should go something like this:
function delMe(){
if (delArray){
for (i =0; i <= delArray.length; i++){
oms.removeMarker(delArray[i]);
delArray[i].setMap(null);
}
this.delArray = [];
}
}
(It's possible you have other problems too, but here's a start).
It's not clear from what you write, but are you using the JS developer console? Google '[your browser] developer console' for more info — it lets you see if errors are causing your map to become unresponsive.

Uncheck dynamical checkbox -> remove marker

I really searched everywhere but I can't find my mistake in my code. I have information that is dynamical loaded into a checkbox (I only have one checkbox on my html) because I do not know at advanced how many checkboxes I will need...
This is my code to check if my checkbox is checked, and what is in it. The value is lat,lng and title
$(".chkbx").on("change", function() {
var selected = new Array();
//marker.setVisible(false);
//map.removeOverlay(marker);
//marker.setMap(null);
$("input:checkbox[name=checkbox]:checked").each(function() {
selected.push($(this).val());
});
console.log(selected);
for(var i=0; i< selected.length ;i++)
{
var current = selected[i].split(';');
var blueIcon = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&' + 'chco=FFFFFF,008CFF,000000&ext=.png';
var siteLatLng = new google.maps.LatLng(current[0], current[1]);
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
icon: blueIcon,
animation: google.maps.Animation.DROP,
title: current[2],
//zIndex: sites[3],
html: current[2]
});
marker.setMap(map);
}
}
});
My markers show on my google map but it is impossible to remove them ... can someone please help me or suggest something?
So for each selected checkbox you create a marker. What you need to do is add those markers into an array that you can then reference later.
// global variable
var markers = [];
$(".chkbx").on("change", function() {
var selected = [];
// loop through all the markers, removing them from the map:
for (var marker in markers) {
marker.setMap(null);
}
// then you probably want to clear out the array, so you can then re-insert markers to it
markers = [];
$("input:checkbox[name=checkbox]:checked").each(function() {
selected.push($(this).val());
});
for(var i=0; i< selected.length ;i++)
{
var current = selected[i].split(';');
var blueIcon = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&' + 'chco=FFFFFF,008CFF,000000&ext=.png';
var siteLatLng = new google.maps.LatLng(current[0], current[1]);
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
icon: blueIcon,
animation: google.maps.Animation.DROP,
title: current[2],
html: current[2]
});
// you don't need this setMap here, you already specified map in your mapOptions:
// marker.setMap(map);
markers.push(marker);
}
});

Change Google maps to re-use single infowindow rather than creating multiple

I have an increasingly complex Google map which plots thousands of points and clusters them. I have an infowindow opening when the user clicks one of the map markers and it all works great. However, one improvement I'd like to make is to force all other infowindows to close when a new one is opened so that only 1 infowindow can be open at once.
I've tried adding some code (if (infowindow) infowindow.close();) into the listener function to do this, but I think the issue is wider in that I'm currently creating an infowindow for each marker, and there is no access to other infowindows on the event which opens a new one. So, from reading around this it would seem to be a better idea to have just one infowindow which gets reused rather than many.
Trouble is, the code is at the edge of what I can really understand, and my experiments in doing this so far have just broken everything.
The code I currently have is as follows:
var _iconCenter = new google.maps.MarkerImage('/css/img/map-marker.png',
new google.maps.Size(38, 48),
new google.maps.Point(0,0),
new google.maps.Point(19, 44));
var shadow = new google.maps.MarkerImage('/css/img/map-marker-shadow.png',
new google.maps.Size(57, 49),
new google.maps.Point(0,0),
new google.maps.Point(7, 44));
var _icon = '/css/img/map-marker-purple.png';
var infowindow;
var markersArray = [];
var map;
var currentPosition = 0;
var currentmarker;
var firstload = true;
var maploaded = false;
var interval = 5000;
var geocoder;
var stylez = [];
function initialize(items,loop,zoom) {
geocoder = new google.maps.Geocoder();
if (items.length > 0) {
var latlng = new google.maps.LatLng(items[0].Lat, items[0].Lng);
var myOptions = {
zoom: zoom,
center: latlng,
//mapTypeControl: false,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
map.setOptions({styles: stylez});
for (var i = 0; i < items.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(items[i].Lat, items[i].Lng),
title: items[i].Title,
icon: _icon,
shadow: shadow,
infocontent: items[i].Description
});
marker.setMap(map);
attachListener(marker,'marker:'+i);
markersArray.push(marker);
}
//set style options for marker clusters (these are the default styles)
mcOptions = {
gridSize: 44
}
var markerCluster = new MarkerClusterer(map, markersArray, mcOptions);
google.maps.event.addListener(map, "tilesloaded", function () {
if(loop == true){
SetLoop();
}
});
function attachListener(marker,content){
google.maps.event.addListener(marker, "click", function () {
var infowindow = new google.maps.InfoWindow();
map.setCenter(new google.maps.LatLng(marker.getPosition().lat(), marker.getPosition().lng()));
infowindow.setContent(content);
infowindow.open(map,this);
});
}
}
}
function SetLoop() {
//This will fire everytime map loads or recenteres
maploaded = true;
if (firstload) {
firstload = false;
Recenter();
}
}
function Recenter() {
//If previous iteration is not loaded completely, wait to avoid errors
//It could happen for slow internet connection
if (maploaded) {
maploaded = false;
} else {
//keep adding 1 second to interval for slow connection till page loads
interval = interval + 1;
setTimeout("Recenter()", interval);
return;
}
if (infowindow != null && currentmarker != null) {
//currentmarker.icon = _icon;
currentmarker.icon = _iconCenter;
currentmarker.setMap(map);
infowindow.close(map, currentmarker);
}
markersArray[currentPosition].icon = _iconCenter;
markersArray[currentPosition].setMap(map);
map.setCenter(new google.maps.LatLng(markersArray[currentPosition].getPosition().lat(), markersArray[currentPosition].getPosition().lng()));
infowindow = new google.maps.InfoWindow({
content: markersArray[currentPosition].infocontent,
size: new google.maps.Size(50, 50)
});
infowindow.open(map, markersArray[currentPosition]);
currentmarker = markersArray[currentPosition];
if (currentPosition >= markersArray.length - 1) {
currentPosition = 0;
} else {
currentPosition++;
}
if (markersArray.length > 1) {
setTimeout("Recenter()", interval);
}
}
Is the best way to re-use the infowindow or is it okay to do this another way? Any help in pointing me in the right direction here would be much appreciated, thanks folks!
Remove the 'var infowindow' declaration from function attachListener(). If you declare it inside the function it becomes local to the function and you create a new instance each time you execute the function. so:
function attachListener(marker,content){
google.maps.event.addListener(marker, "click", function () {
// marker.getPosition() already returns a google.maps.LatLng() object
map.setCenter(marker.getPosition());
infowindow.close();
infowindow.setContent(content);
infowindow.open(map,this);
});
}
and instead, declare it as a global variable:
var _icon = '/css/img/map-marker-purple.png';
var infowindow = new google.maps.InfoWindow();
//...etc
so that you have only one infowindow object in the whole application

Display Number on Marker for Google Maps

All,
I've got the following code to display my markers on my maps:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function'){
window.onload = func
} else {
window.onload = function() {
oldonload();
func();
}
}
}
var map,
infowin=new google.maps.InfoWindow({content:'moin'});
function loadMap()
{
map = new google.maps.Map(
document.getElementById('map'),
{
zoom: 12,
mapTypeId:google.maps.MapTypeId.ROADMAP,
center:new google.maps.LatLng(<?php echo $_SESSION['pav_event_latitude']; ?>,
<?php echo $_SESSION['pav_event_longitude']; ?>)
});
addPoints(myStores);
}
function addPoints( points )
{
var bounds=new google.maps.LatLngBounds();
for ( var p = 0; p < points.length; ++p )
{
var pointData = points[p];
if ( pointData == null ) {map.fitBounds(bounds);return; }
var point = new google.maps.LatLng( pointData.latitude, pointData.longitude );
bounds.union(new google.maps.LatLngBounds(point));
createMarker( point, pointData.html );
}
map.fitBounds(bounds);
}
function createMarker(point, popuphtml)
{
var popuphtml = "<div id=\"popup\">" + popuphtml + "<\/div>";
var marker = new google.maps.Marker(
{
position:point,
map:map
}
);
google.maps.event.addListener(marker, 'click', function() {
infowin.setContent(popuphtml)
infowin.open(map,marker);
});
}
function Store( lat, long, text )
{
this.latitude = lat;
this.longitude = long;
this.html = text;
}
var myStores = [<?php echo $jsData;?>, null];
addLoadEvent(loadMap);
</script>
This works great. However I'm trying to say add a number over the marker so that people can relate the number on my site with the marker in Google Maps. How can I go about creating the number over top of my markers (on top of the actual icon and not in an information bubble)?
Any help would be greatly appreciate! Thanks in advance!
EDIT: This API is now deprecated, and I can no longer recommend this answer.
You could use Google's Charts API to generate a pin image.
See: http://code.google.com/apis/chart/infographics/docs/dynamic_icons.html#pins
It'll make and return an image of a marker from the parameters you specify. An example usage would be: https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=2|FF776B|000000
To implement it into your Google Map, it can be added into the new Marker() code:
var number = 2; // or whatever you want to do here
var marker = new google.maps.Marker(
{
position:point,
map:map,
icon:'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld='+number+'|FF776B|000000',
shadow:'https://chart.googleapis.com/chart?chst=d_map_pin_shadow'
}
);
EDIT:
For quite some time now, map markers have an option called label available.
var marker = new google.maps.Marker({
position:point,
map:map,
label: "Your text here."
});
Labels themselves have few options to play with. You can read more about it here.
Original answer
Here is a service similar to one described by Rick - but still active and you can upload your own marker image.
Service is no longer available.

Removing a Marker from an array in Google maps v3.0 problem

I've got this problem when removing a Marker from an array. I click on the map and place markers where i have clicked, the markers are then saved in an array. When removing them it only works in the order i have placed them but backwards, that means i place 1 2 3 but have to remove them like 3 2 1.
If i try to remove the markers in random order, the first one is removed, but then the others just stop working, the listener still works, but it seems like the forloop doesnt find the other markers in the array.
Any ideas? I'm completely lost.
Here is the code:
var map;
var tempLatLng;
var zoomLevel;
var markers = [];
var zoomLevels = [];
var count = -1;
var nullLatlng = new google.maps.LatLng(84.52,45.16);
var nullMarker = new google.maps.Marker({
position: nullLatLng,
});
function initialize() {
var myLatlng = new google.maps.LatLng(55.605629745598904,13.000441789627075);
var myOptions = {
zoom: 17,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel:false
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//Puts a listener on the map, when clicking on the map, it places a marker.
google.maps.event.addListener(map, 'click', function(event) {
zoomLevel = map.getZoom();
document.getElementById("zoom").value = zoomLevel;
tempLatLng = event.latLng;
setTimeout("placeMarker(tempLatLng)", 800); //placeMarker is called with a duration so that //doubleclicking doesn't bother the placement.
});
}
//Function to place markers.
function placeMarker(location) {
if(zoomLevel == map.getZoom()){
if(true){
var marker1 = new google.maps.Marker({
position: location,
map: map,
draggable:true
});
count = count + 1;
markers[count] = marker1;
document.getElementById("count").value = count;
google.maps.event.addListener(marker1,'rightclick', function(event){
document.getElementById("test2").value = "funkar";
for(var i = 0 ;i < markers.length ;i++){
if(markers[i].getTitle() == marker1.getTitle()){
marker1.setMap(null);
document.getElementById("markerpos").value = markers[i].getTitle();
document.getElementById("test1").value = markers[i].getTitle();
count = count - 1;
document.getElementById("count").value = count;
markers[i] = nullMarker;
}
}
});
marker1.setTitle(location.toString());
}
map.setCenter(location);
}
}
Here is the JSFiddle Demo:
Basically, you were using var count to keep track of the number of markers. You can do markers.length for that. Instead of using markers[count] you can use native array's push method to add element into the array. To remove use splice(i, 1); where i is the element's position and remove 1 element from that position. Also, to check if two markers are equal or the "same" instead using getTitle() use === which does:
is exactly equal to (value and type)
The problem is if you create two or more markers on the same position it would remove both markers but in reality you only remove one of the two "clones" and thus leaving a marker un-removable. This is caused by using getTitle which returns lat lng and if you have two markers w/ same lat lng you have an issue. Also, i changed, within your onclick function, marker1 to this which are referring to the same object for readability.
//Function to place markers.
function placeMarker(location) {
if (zoomLevel == map.getZoom()) {
if (true) {
var marker1 = new google.maps.Marker({
position: location,
map: map,
draggable: true
});
count = count + 1;
markers.push(marker1);
document.getElementById("count").value = markers.length;
google.maps.event.addListener(marker1, 'rightclick', function(event) {
document.getElementById("test2").value = "funkar";
for (var i = 0; i < markers.length; i++) {
if (markers[i] === this) {
this.setMap(null);
document.getElementById("markerpos").value = markers[i].getTitle();
document.getElementById("test1").value = markers[i].getTitle();
markers.splice(i, 1);
document.getElementById("count").value = markers.length;
}
}
});
marker1.setTitle(location.toString());
}
map.setCenter(location);
}
}