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!!

4 comments:

  1. Josh, I didn't use your array to add multiple points to my map but, I did go back to see how you added one and used that. My map used to have a marker but now, for some reason, it doesn't ... so I added one per your explaination. Thanks.

    ReplyDelete
  2. Thanks, been fighting some code to add multiple markers to my map. Hopefully this will get me all fixed up before the presentation of iteration #3.

    ReplyDelete
  3. That would have been a nice feature to add on my page. I may continue to play around with my IRAM dating service so I can add the actual movie api

    ReplyDelete
  4. I am in the same boat as James, adding multiple markers on my map. Thank you for this post and the code.

    ReplyDelete