-2

I have a simple array containing name of cities. I'm trying to loop through this array and add markers linked by Polylines on the Google Map.

Here is my code:

 function addMarkerCity(cities) {
   $.each(cities, function(index, value) {
    geocoder.geocode({'address': value}, function(results, status) {
     if (status == google.maps.GeocoderStatus.OK) {
       var cityPosition = results[0].geometry.location;
       flightRoute.push(cityPosition);
       var currentMarker = map.addMarker({
         position: cityPosition
       });
     });
   });
 });
}

The function addMarkerCity works fine and triggered by a JQuery event click() button. I'm using the array flightRoute to store each position of each marker and then pass it to the function which will create the polyline between the 2 markers.

The problem now is that I only see the polyline on the map if I click twice on the button to make it work.

When I'm doing:

console.log(flightRoute);

The array flightRoute is equal to [] first and then I can see the LatLng of the 2 previously created markers. Can someone tell me what I'm doing wrong, to get the position inside flightRoute and display straight away the markers. I'm very close to get the result that I want.

Nizar B.
  • 3,098
  • 9
  • 38
  • 56
  • 1
    Can you post a working example? JSfiddle or something similar – not_a_bot May 22 '15 at 22:31
  • Wouldn't you need to press the button twice to get 2 markers, which would then give you a polyline? Can't have a line with just 1 point. – not_a_bot May 22 '15 at 22:36
  • There is no click function (or map for that matter) in your posted code. What does your click function do? Please provide a [Minimal, Complete, Tested and Readable example](http://stackoverflow.com/help/mcve) that demonstrates the issue. – geocodezip May 23 '15 at 04:02
  • The function posted has syntax errors. Please provide a [Minimal, Complete, Tested and Readable example](http://stackoverflow.com/help/mcve) that demonstrates the issue. – geocodezip Jan 07 '16 at 20:28
  • Sounds like you aren't accounting for the asynchronous nature of the Geocoding Service. – geocodezip Jan 07 '16 at 20:39

1 Answers1

-1

In order to add points to a polyline dinamically

  1. you need to have an array of the type google.maps.MVCArray

    var points = new google.maps.MVCArray();

  2. you need to pass that mvcarray to the polyline

    var polyline = new google.maps.Polyline({ path: points });