[GIS] Convert WKT to GeoJSON with Leaflet

convertgeojsonleafletPHPwell-known-text

I have a point type WKT geometry column in a MySQL table storing the location of some stores.

I want to display it on a Leaflet map on my website. I've found plenty of tutorials to doing this on leaflet official website from GeoJSON data.

But I found no precise documentation which clearly explains how to convert WKT to GeoJSON…even if it seems to be a very important part of the process.

Does someone know a good source which fills this gap or can explain to me how to do this in PHP or JavaScript?

Best Answer

If you've already got WKT, then you might considering using the JavaScript library, Wicket, to go straight from your WKT to Leaflet features. As this example shows, you can pass in a WKT string and a style/options object, and Wicket will return a feature object you can attach directly to a Leaflet FeatureGroup, etc.

This example assumes two things: 1) You have an existing layer or featureGroup already and instantiated and added to your map, and 2) you have an existing icon style for your markers. In this case I just assumed the greenIcon marker style from the official Leaflet documentation.

var wkt_geom = "POINT(34.0218531, -81.0707438)";
var wicket = new Wkt.Wkt();
wicket.read(wkt_geom);

// "greenIcon from official documentation noted above.
var feature = wicket.toObject({icon: greenIcon});

// Presumably featureGroup is already instantiated and added to your map.
featureGroup.addLayer(feature);