Show a moving marker on the map

后端 未结 3 1994
星月不相逢
星月不相逢 2020-12-28 11:24

I am trying to make a marker move(not disappear and appear again) on the map as a vehicle moves on the road.

I have two values of latLng and I want

相关标签:
3条回答
  • 2020-12-28 11:59

    You can use marker-animate-unobtrusive library to make markers smoothly transition from one location to another (instead of reappearing).

    You could initialize your marker like that:

    var marker = new SlidingMarker({
       //your original marker options
    });
    

    Just call marker.setPosition() each time new vehicle's coordinate arrive.

    P.S. I'm the author of the library.

    0 讨论(0)
  • 2020-12-28 11:59

    Why not keep the existing Marker/ MarkerImage and call setPosition() to move it, either on a timer or as the position changes?

    Deleting it & recreating it is what causes it to flash/ flicker and eventually crash. If you keep the same instance but just move it, you should do much better.

    See: Marker.setPosition()

    https://developers.google.com/maps/documentation/javascript/reference#Marker

    0 讨论(0)
  • 2020-12-28 12:17

    For the marker to move relatively smoothly, you need to

    • Update more than every 1/10 fraction of the polyline (at least every few pixels)
    • Call the update method more frequently
    • Don't delete and re-add the marker

    For example, something like:

    var counter = 0;
    interval = window.setInterval(function() { 
      counter++;
      // just pretend you were doing a real calculation of
      // new position along the complex path
      var pos = new google.maps.LatLng(35, -110 + counter / 100);
      marker.setPosition(pos);
      if (counter >= 1000) {
        window.clearInterval(interval);   
      }
    }, 10);
    

    I made a simple example at http://jsfiddle.net/bmSbU/2/ which shows a marker moving along a straight path. If this is what you want, most of your code above regarding where along the line you are can be reused (or check out http://broady.github.io/maps-examples/points-along-line/along-directions.html )

    0 讨论(0)
提交回复
热议问题