I am working on a map where the user can click unpon, creating new markers. For each marker, some information should be displayed on the side panel: latitude, longitude and name. The name is created by reverse geocoding. I created an array of markers and everything looks fine, but the title of the first marker in the array is always "undefined". No problem with coords: just the first title of the element! The title is regularly displayed in the infowindow window ... But this is "undefined" in the first element of the array. Here is my code:
<script> var map; var markers = []; var rome = new google.maps.LatLng(41.9012, 12.4751); var infowindow; var geocoder; function loadMap(){ var myOptions = { zoom: 15, center: rome, mapTypeId: google.maps.MapTypeId.SATELLITE }; map = new google.maps.Map( document.getElementById('canvas'), myOptions ); google.maps.event.addListener(map, 'click', function(evt){ addMarker( evt.latLng ); }); } function addMarker( location ){ var marker = new google.maps.Marker({ position: location, map: map }); marker.setMap( map ); openInfoWindow( marker ); markers.push( marker ); updateList( marker ); } function openInfoWindow( marker ){ geocoder = new google.maps.Geocoder(); geocoder.geocode({'location': marker.getPosition()}, function(results, status){ if (status == google.maps.GeocoderStatus.OK) { address = results[0].formatted_address; }else{ address("Address not found"); } var infowindow = new google.maps.InfoWindow({ content: address }); infowindow.open(map, marker); marker.setTitle(address); console.log(address); }); } function updateList( marker ){ var lat, lng, title; if( markers.length > 0 ){ $('#sidebar').html('<ul></ul>'); for( var i = 0; i < markers.length; i++ ){ lat = markers[i].getPosition().lat(); lng = markers[i].getPosition().lng(); title = markers[i].getTitle(); var html = '<li>Lat: ' + lat + '<br />Lng: ' + lng + '<br />' + title + '</li>'; $(html).prependTo('#sidebar ul'); }</script>
Where am I wrong?
source share