Robson
Robson

Reputation: 1277

Geocode two addresses and create map js googlemaps api v3

I've got a problem with rendering my map. I want to display two markers on the map dynamically.

Map is rendering but markers aren't display.

Here's my code for map:

 <script type="text/javascript">
            // When the window has finished loading create our google map below
            google.maps.event.addDomListener(window, 'load', init);

            function init() {

                var delay = 100;
              var infowindow = new google.maps.InfoWindow();
                var mapOptions = {
                    // How zoomed in you want the map to start at (always required)
                    zoom: 11,

                    // The latitude and longitude to center the map (always required)
                    center: new google.maps.LatLng(51.507351, -0.127758), // New York

                    // How you would like to style the map.
                    // This is where you would paste any style found on Snazzy Maps.
                    styles: [{
                        "featureType": "water",
                        "elementType": "geometry",
                        "stylers": [{"color": "#e9e9e9"}, {"lightness": 17}]
                    }, {
                        "featureType": "landscape",
                        "elementType": "geometry",
                        "stylers": [{"color": "#f5f5f5"}, {"lightness": 20}]
                    }, {
                        "featureType": "road.highway",
                        "elementType": "geometry.fill",
                        "stylers": [{"color": "#ffffff"}, {"lightness": 17}]
                    }, {
                        "featureType": "road.highway",
                        "elementType": "geometry.stroke",
                        "stylers": [{"color": "#ffffff"}, {"lightness": 29}, {"weight": 0.2}]
                    }, {
                        "featureType": "road.arterial",
                        "elementType": "geometry",
                        "stylers": [{"color": "#ffffff"}, {"lightness": 18}]
                    }, {
                        "featureType": "road.local",
                        "elementType": "geometry",
                        "stylers": [{"color": "#ffffff"}, {"lightness": 16}]
                    }, {
                        "featureType": "poi",
                        "elementType": "geometry",
                        "stylers": [{"color": "#f5f5f5"}, {"lightness": 21}]
                    }, {
                        "featureType": "poi.park",
                        "elementType": "geometry",
                        "stylers": [{"color": "#dedede"}, {"lightness": 21}]
                    }, {
                        "elementType": "labels.text.stroke",
                        "stylers": [{"visibility": "on"}, {"color": "#ffffff"}, {"lightness": 16}]
                    }, {
                        "elementType": "labels.text.fill",
                        "stylers": [{"saturation": 36}, {"color": "#333333"}, {"lightness": 40}]
                    }, {
                        "elementType": "labels.icon",
                        "stylers": [{"visibility": "off"}]
                    }, {
                        "featureType": "transit",
                        "elementType": "geometry",
                        "stylers": [{"color": "#f2f2f2"}, {"lightness": 19}]
                    }, {
                        "featureType": "administrative",
                        "elementType": "geometry.fill",
                        "stylers": [{"color": "#fefefe"}, {"lightness": 20}]
                    }, {
                        "featureType": "administrative",
                        "elementType": "geometry.stroke",
                        "stylers": [{"color": "#fefefe"}, {"lightness": 17}, {"weight": 1.2}]
                    }]
                };

                // Get the HTML DOM element that will contain your map
                // We are using a div with id="map" seen below in the <body>
                var mapElement = document.getElementById('map');

                // Create the Google Map using our element and options defined above
                var map = new google.maps.Map(mapElement, mapOptions);

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

                var geocoder = new google.maps.Geocoder();

                  function geocodeAddress(address, next) {
                    geocoder.geocode({address:address}, function (results,status)
                      {
                         if (status == google.maps.GeocoderStatus.OK) {
                          var p = results[0].geometry.location;
                          var lat=p.lat();
                          var lng=p.lng();
                          createMarker(address,lat,lng);
                        }
                        else {
                           if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                            nextAddress--;
                            delay++;
                          } else {
                                        }
                        }
                        next();
                      }
                    );
                  }
                 function createMarker(add,lat,lng) {
                   var contentString = add;
                   var marker = new google.maps.Marker({
                     position: new google.maps.LatLng(lat,lng),
                     map: map,
                           });

                  google.maps.event.addListener(marker, 'click', function() {
                     infowindow.setContent(contentString);
                     infowindow.open(map,marker);
                   });

                   bounds.extend(marker.position);

                 }
                 var locations = ['London, United Kingdom', 'Liverpool, United Kingdom'];

                var nextAddress = 0;
                  function theNext() {
                    if (nextAddress < locations.length) {
                      setTimeout('geocodeAddress("'+locations[nextAddress]+'",theNext)', delay);
                      nextAddress++;
                    } else {
                      map.fitBounds(bounds);
                    }
                  }
                  theNext();

            }
    </script>

How can I display these markers correctly ? Many thanks for suggestions and any feedback where I did some mistakes.

Upvotes: 0

Views: 91

Answers (2)

geocodezip
geocodezip

Reputation: 161404

I get a javascript error with the posted code: Uncaught ReferenceError: geocodeAddress is not defined

All your code is local to the init function. If you use the setTimeout syntax:

var timeoutID = window.setTimeout(code[, delay]);

code

An optional syntax allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is not recommended for the same reasons that make using eval() a security risk.

That code is executed in the global context.

proof of concept fiddle (map styling removed as not relevant to the issue)

code snippet:

google.maps.event.addDomListener(window, 'load', init);
// global variables
var nextAddress = 0;
var delay = 100;
var locations = ['London, United Kingdom', 'Liverpool, United Kingdom'];
var bounds = new google.maps.LatLngBounds();
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
var map;

function init() {
  var mapOptions = {
    // How zoomed in you want the map to start at (always required)
    zoom: 11,
    // The latitude and longitude to center the map (always required)
    center: new google.maps.LatLng(51.507351, -0.127758), // New York
  };

  // Get the HTML DOM element that will contain your map
  // We are using a div with id="map" seen below in the <body>
  var mapElement = document.getElementById('map');
  // Create the Google Map using our element and options defined above
  map = new google.maps.Map(mapElement, mapOptions);
  theNext();
}

function createMarker(add, lat, lng) {
  var contentString = add;
  var marker = new google.maps.Marker({
    position: new google.maps.LatLng(lat, lng),
    map: map,
  });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(contentString);
    infowindow.open(map, marker);
  });
  bounds.extend(marker.position);
}

function geocodeAddress(address, next) {
  geocoder.geocode({
    address: address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      var p = results[0].geometry.location;
      var lat = p.lat();
      var lng = p.lng();
      createMarker(address, lat, lng);
    } else {
      if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
        nextAddress--;
        delay++;
      } else {}
    }
    next();
  });
}

function theNext() {
  if (nextAddress < locations.length) {
    setTimeout('geocodeAddress("' + locations[nextAddress] + '",theNext)', delay);
    nextAddress++;
  } else {
    map.fitBounds(bounds);
  }
}
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

Upvotes: 0

Gabriel Glenn
Gabriel Glenn

Reputation: 1264

setTimeout('geocodeAddress("'+locations[nextAddress]+'",theN‌​ext)', delay);

The geocodeAddress function will not be exectued, as setTimeout first parameter should be a function.

Nevertheless,

  setTimeout(geocodeAddress(locations[nextAddress], theN‌​ext), delay);

Is still not looking good, because geocodeAddress will not be executed with the expected delay, but right when setTimeout will evaluate it's first parameter. Try with a delay of 3 seconds, you will see what I mean.

Upvotes: 1

Related Questions