简体   繁体   中英

Google Map dynamics markers and polylines

The user insert the city of departure and destination in 2 text input, then click on the button to display on the Google Map 2 markers corresponding to the inserted cities and a Polyline between those 2 points.

Here is my code:

 //Global array
 var pathArray = [];
 var cities = [ origin, destination ];
 $('#button').on("click", function()  {
   reverseGeocodeCities(cities);
 });

  function reverseGeocodeCities(cities) {
   $.each(cities, function(index, value) {
     geocoder.geocode({'address': value}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        addMarkerCity(results[0].geometry.location);
     }
    });
  });
  //Create the polyline just after the loop.
   addPolyline();
 }

  function addMarkerCity(cityPosition) {
    var currentMarker = map.addMarker({
      position: cityPosition
   });
   //Add the position of the marker into the global pathArray used by addPolylineCity function.
   pathArray.push(currentMarker.getPosition());
 }

  function addPolylineCity() {
    console.log(pathArray); //Display "[]" at the first click.
    var polyline = map.drawPolyline({
    path: pathArray,
  });

I have 2 problems with this code: The first one is, when the user click once on the button, the markers are displayed well on the Google Map but not the polyline between the 2 markers. I have to click twice on the button to make the polyline visible. To create the polyline, I'm using the global array pathArray containing each markers position. It always display an empty array at the first click and then the proper position of the markers after the second click on the button.

The second problem is that I'm doing a simple symbol animation on the created polyline but the flow direction change time to time, if I want to do London to New York, the symbol should slide from London to New york and not the reverse (I removed this part for code simplicity). Please note that I'm using Gmaps wrapper to use Google Map features.

Thanks for your help if you know what I'm doing wrong with my code.

You are creating the polyline first and then the markers, so the polyline does not appear

               if (pathArray.length == 2) {
                addPolylineCity();
           }; //hardcode 

An example JSFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM