Showing posts with label GMarker Array. Show all posts
Showing posts with label GMarker Array. Show all posts

Nov 29, 2009

Adding Multiple Google Map Markers into an Array

Some people may ask why you would want to add Google Map markers into an array and I would not have a good answer. Today, however is a new day and for me I wanted to be able to add multiple markers on a map and then remove specific markers with a click of a button.

You could use the command MyMap.clearOverlays() to clear all markers at one time, but this would hinder you if you want to remove only certain markers. To remove certain markers all you need to do is add your markers into an array and then refer to that marker in the array using the command MyMap.removeOverlay(markersArray[i]). Although this looks foreign now, I will take you through adding markers and then removing them.


The first thing you want to do is add a marker into an array. Below is the code







Code Broken Down:
var markersArray = [];
This statement creates an array and then initializes the array with the = []. This will need to be placed outside any functions in order to create a global variable

var point = new GLatLng(42.251012,-83.625011);
var marker = new GMarker(point);
map.addOverlay(marker);
Adds a marker to an exact point on a google map. This code is actually a repeat of the code shown in my previous post Adding a Marker to a Google Map. Please review this post if you need a refresher.

markersArray.push(marker);
This statements pushes your added marker into thearray so you can reference it at a later time

For me I wanted to remove a marker from a google map. Now that I added it to my array all I need to do to reference this marker when I want to remove it from a google maps using the following command.
MyMap.removeOverlay(markersArray[i])

As an added bonus, If you want to see how many markers are in your array you can use the command
alert(markersArray.length);


I have incorporated this into my group project and will show the functionality at work during our presentation.

Enjoy!!