Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LeafletJS multi-polyline in Typescript

I'm trying to use the demo from http://leafletjs.com/reference-1.2.0.html#polyline

// create a red polyline from an array of LatLng points
var latlngs = [
    [45.51, -122.68],
    [37.77, -122.43],
    [34.04, -118.2]
];
var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
// zoom the map to the polyline
map.fitBounds(polyline.getBounds());

However, it's throwing me an error:

[ts]
Argument of type 'number[][]' is not assignable to parameter of type 'LatLngExpression[]'.
  Type 'number[]' is not assignable to type 'LatLngExpression'.
    Type 'number[]' is not assignable to type '[number, number]'.
      Property '0' is missing in type 'number[]'.

is something else needed when using leaflet with Angular/TypeScript?

like image 757
Travisty Avatar asked Aug 28 '26 19:08

Travisty


1 Answers

Looks like your code is fine, but the types are a little finicky. As the compiler notes, number[] is not assignable to [number, number], which makes total sense (as an empty array [] should assign to number[] but not [number, number]).

Anyway, all you have to do is give typescript a hint that you are actually passing the right type. I would recommend you declare it on your variable, eg:

var latlngs: [number, number][] = [
    [45.51, -122.68],
    [37.77, -122.43],
    [34.04, -118.2]
];

Or, if in your actual use case that value comes from somewhere else, you can just cast it:

var polyline = L.polyline(latlngs as [number, number][], {color: 'red'}).addTo(map);
like image 76
CRice Avatar answered Aug 31 '26 17:08

CRice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!