0

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.

5
  • Did you try to remove all unrelated code and just create a map with two markers ? There is lot of things in your code, you should be able to narrow it a bit. Commented Sep 16, 2016 at 8:52
  • 1
    why setTimeout('geocodeAddress("'+locations[nextAddress]+'",theNext)', delay); ? This just looks bad ! geocodeAddress will not be executed with the delay, but right at the evaluation of setTimeout Commented Sep 16, 2016 at 9:00
  • Yeah, you're right, that was the problem, I don't know why it's wrapped by string, need coffee :) Thanks for it ! Commented Sep 16, 2016 at 9:03
  • 1
    You're welcome, but it's still bad, even if it's written setTimeout(geocodeAddress("'+locations[nextAddress]+'",theN‌​ext), delay) Commented Sep 16, 2016 at 9:05
  • I rewrite it by setTimeout(geocodeAddress(locations[nextAddress],theNext), delay); Commented Sep 16, 2016 at 9:07

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.