How to add and delete map markers for google maps

I am getting addresses from a database and I want to geolocate each one and create a new map marker for each. Does anybody know an easy way to do this?
LVL 9
BobHavertyComhAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Tom BeckCommented:
Here's a self-contained example that draws from an array of locations to drop markers.
<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
    <style type="text/css">
      html { height: 100% }
        body { height: 100%; margin: 0; padding: 0 20px }
        #map-canvas { height: 70%; width: 80% }
		#list li { list-style: none }
      </style>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
    <script src="http://maps.googleapis.com/maps/api/js?sensor=false&v=3" type="text/javascript"></script>

    <script>
			var startingPoint = 123;
            var bounds = new google.maps.LatLngBounds();
			var geocoder,map;		
			
      $(document).ready(function() { 
            map = new google.maps.Map(document.getElementById('map-canvas'));
			geocoder = new google.maps.Geocoder();
                  geocoder.geocode({'address': 'USA'}, function(results, status) {
                  map.fitBounds(results[0].geometry.viewport);
            });
			geolocate();
	  });

            var chunk = 0, inerval;
			
            var locations = [
                  {
                        address: '48 W Seegers Rd, Arlington Heights, IL 60005',
                        company: 'Company B'
                  },
                  {
                        address: '220 N Michigan Ave, Chicago, IL 60601',
                        company: 'Company A'
                  },
                  {
                        address: '1670 Barclay Blvd, Buffalo Grove, IL 60089',
                        company: 'Company C'
                  },
                  {
                        address: '1665 Elk Blvd, Des Plaines, IL 60016',
                        company: 'Company D'
                  },
                  {
                        address: '1800 W Central Rd, Mount Prospect, IL 60056',
                        company: 'Company E'
                  },
                  {
                        address: '3400 Dundee Rd, Northbrook, IL 60062',
                        company: 'Company F'
                  },
                  {
                        address: '3100 Dundee Rd Ste 704, Northbrook, IL 60062',
                        company: 'Company G'
                  },
                  {
                        address: '188 W Randolph St Ste 600, Chicago, IL 60601',
                        company: 'Company H'
                  },
                  {
                        address: '69 W Washington St, Chicago, IL 60602',
                        company: 'Company I'
                  },
                  {
                        address: '269 W Washington St, Chicago, IL 60601',
                        company: 'Company J'
                  }
            ];
			
			function geolocate(){
            	inerval = setInterval(delayCode, 700);
			}
			
            function delayCode() {
				var step = 1;
				if (chunk < locations.length) {
					  for (x = chunk; x < locations.length && x < chunk + step; x++) {
							codeAddress(locations[x]);
					  }
					  chunk += step;
				} else{
					  clearInterval(inerval);					  
				}
            }            

            function codeAddress(address) {
				  var loc = address;
                  geocoder.geocode({ 'address':address.address }, function(results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                        var location = results[0].geometry.location;
                        address.location = location;
						displayMarker();
                        }
                        else {
                              alert('Geocode was not successful for the following reason: ' + status);
                        }
                  });
            }
			
			var count = 0;
			function displayMarker() {
				var marker1 = new google.maps.Marker({map: map, position: locations[count].location, title: locations[count].company, address: locations[count].address});
				var infowindow1 = new google.maps.InfoWindow();
				google.maps.event.addListener(marker1, "click", function () {
					infowindow1.setContent('<b>' + this.title + '</b><br />' + this.address);
					infowindow1.open(map, this);
				});
				//extend the bounds of the map to include this marker
				bounds.extend(locations[count].location);
				//zoom the map to nicely fit the bounds of the two closest markers and the starting point
                map.fitBounds(bounds);
				count++;
			}
    </script>
    
  </head>
  <body>
  <h3>Map from Array of Addresses</h3>
  	
    <div id="map-canvas"></div>
    <ul id="list">
    </ul>
  </body>
</html>

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
BobHavertyComhAuthor Commented:
That looks just about like what I was looking for and it should be plenty of info for me to figure out and use.  If I run into specific questions while implementing it the way I need it, I'll ask a new question. Thanks Tom.
Tom BeckCommented:
Sounds like a plan.

The thing to remember about using Google's Geocoder is that Google will block use of it if you hit them with multiple rapid-fire requests. The public version is very limited. That's the purpose of the delay in the code. Without the delay you might get two requests fulfilled and the remaining eight will be denied. You can play with the delay interval to see what they will tolerate. In the code step is the number of requests per connection. As written I'm sending 1 request every 700 ms. Two requests every 1000 ms will be quicker if Google allows it.

Thanks for the points.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Google Apps

From novice to tech pro — start learning today.