# Given an array of geojson coordinates, how can I translate the lat/long values an draw its polygon to a canvas tag?

I’m learning, as a project I want to learn how to create and draw a polygon in canvas give a set of geojson coordinates? I have no idea what the steps are to make this happen.

Here is the geojson code I created using geojson.io

``````{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"stroke": "#555555",
"stroke-width": 2,
"stroke-opacity": 1,
"fill": "#555555",
"fill-opacity": 0.5
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-1.910746693611145,
50.743831635778356
],
[
-1.9105897843837738,
50.74381169283351
],
[
-1.9105750322341917,
50.743852851667825
],
[
-1.9105388224124908,
50.743847335537495
],
[
-1.91052608191967,
50.743887645705726
],
[
-1.9107212126255035,
50.74391268042433
],
[
-1.910746693611145,
50.743831635778356
]
]
]
}
}
]
}
``````

It is a simple shape And I would like to take the coordinates and transform them to a unit measurement I can then take and draw it using canvas context, using `moveTo()`, `lineTo()`

Any help will be much appreciated

You can use GitHub - d3/d3-geo: Geographic projections, spherical shapes and spherical trigonometry. ; the geoPath method creates a path generator, and can take in a projection (mapping the coordinates to the screen) and a context (to draw on canvas).

For example:

``````
const context = canvas.getContext("2d");
const projection = d3.geoMercator().fitExtent([[ 10, 10], [ 950, 590]], GeoJSON);
const path = d3.geoPath(projection, context);

context.beginPath();
path(GeoJSON);
context.fillStyle = "#eee";
context.fill();
context.stroke();
``````

However you might be surprised because the winding order of the polygon is the opposite of what d3-geo expects. As a consequence, I had to apply “.reverse()” on its coordinates—there are better ways to do this, but I hope this gets you started.

An alternative is to draw the path yourself with context.moveTo and context.lineTo. You can use the projection directly on the coordinates: projection([lon, lat]) will return screen coordinates as [x,y]. But projecting spherical shapes is usually quite more complicated than this.

Thank you very much!

Can you explain a bit more how to do this? this is exactly what I want to achieve

I’ve added a second example to my notebook.

Got it working! thank you

Where the numbers for this line come from?
`geoMercator().scale(208228918).translate([6944268, 214692512])`

they are given by

d3.geoMercator().fitExtent([[ 10, 10], [ 950, 590]], GeoJSON);

which adjusts the scale and translate of the projection to make the data fit the extent