0

I have been using react leaflet succesful with Int/Float coordinates like [51.505, -0.09] however, i have longitude and Latitude indicator included on my coordinates like ['51.505W', '-0.09S'].

First options runs well with this code.

const position = [51.505, -0.09]
        
render(
  <MapContainer center={position} zoom={13} scrollWheelZoom={false}>
    <TileLayer
      attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
    />
    <Marker position={position}>
      <Popup>
        A pretty CSS3 popup. <br /> Easily customizable.
      </Popup>
    </Marker>
  </MapContainer>
)

Thie second options breaks with error Invalid LatLng object How best can i handle this

Mbanda
  • 968
  • 11
  • 21

1 Answers1

0

Leaflet, and by extension react-leaflet, expects latitude longitude to simple numbers, either in the form of an array of 2 numbers [number, number], or an object in the format { lat: number, lng: number }. Coordinates like ['51.505W', '-0.09S'] don't fit that pattern. But they can be easily transformed with a simple function that strips the letter character from the string and returns a number:

function transformCoords(pair) {
  return pair.map(coordString => {
    return Number(
      coordString
        .replace('N', '')
        .replace('S', '')
        .replace('E', '')
        .replace('W', '')
    )
  })
}

This will take in an array of the format ['51.505W', '-0.09S'] and will return an array like [51.505, -0.09], which can then be properly fed to a Marker position prop:

const position = ['51.505W', '-0.09S']
        
render(
  <MapContainer ...>
    <Marker position={transformCoords(position}) />
  </MapContainer>
)
Seth Lutske
  • 9,154
  • 5
  • 29
  • 78
  • Thank you @seth for your input, those 2 will give you a totally different position, a more realistic example is `['36.837768E', '1.30315S']` vs `['36.837768', '1.30315']` – Mbanda Jun 14 '21 at 06:13
  • I recommend you read [Positive/Negative Latitude and Longitude values vs. Cardinal Directions](https://stackoverflow.com/questions/4536996/positive-negative-latitude-and-longitude-values-vs-cardinal-directions) - if you're using decimal coordinates, you should be using positive and negative, not cardinal direction character markers. At any rate, you can always flip the sign for any coordinate that has a `S` or `W` attached to it. – Seth Lutske Jun 14 '21 at 14:19