Geo add markers dynamically

by fangyang

HTML

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false"></script>
 <div id="panel">
      <input id="address" type="textbox" value="Sydney, NSW">
      <input type="button" id="geocode" value="Geocode" onclick="codeAddress()">
    </div>
    <div id="map-canvas" style="width:100%;height:400px"></div>

CSS

html, body, #map-canvas {
        height:400px,
		width:100%;
        margin: 0px;
        padding: 0px
      }
      #panel {
        position: absolute;
        top: 5px;
        left: 50%;
        margin-left: -180px;
        z-index: 5;
        background-color: #fff;
        padding: 5px;
        border: 1px solid #999;
      }

JavaScript

var geocoder;
var map;

//Below line can be used if you are not using jquery
//google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
  geocoder = new google.maps.Geocoder();
  codeAddress();
}

$(document).ready(function(){
    initialize();
    $("#geocode").click(function(){
    codeAddress();
    });
});

var bounds = new google.maps.LatLngBounds();

function codeAddress() {
 var address = document.getElementById('address').value;
    geocoder.geocode({
        'address': address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var myOptions = {
                zoom: 16,
                center: results[0].geometry.location,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
			if(!map)	{
            map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);}

            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
            
			bounds.extend(marker.position);
			map.fitBounds(bounds);
			 google.maps.event.addListener(marker,'mouseover',   ( function(marker) {
            return function() {
               var infowindow = new google.maps.InfoWindow();
              //  alert("hi");
                var content = '<div class="map-content"><h3>' + address + '</h3> </div>';
              infowindow.setContent(content);
              infowindow.open(map, marker);
            }
          })(marker));
        } else {
		  alert('Geocode was not successful for the following reason: ' + status);
		}
    });
}