круги geojson, поддерживаемые или нет?

когда я смотрю спецификации GeoJson, я вижу, что круги поддерживаются:

http://geopriv.dreamhosters.com/geojson/geojson-spec.html#circleExample

когда я пробую код в geojsonlint (http://geojsonlint.com/) однако, это дает мне ошибку.

вход:

{ 
"type": "Circle",
"coordinates": [4.884, 52.353],
"radius": 200
}

выдает:

"Circle" is not a valid GeoJSON type. 

Я хочу показать различные места интересов с диапазоном влияния на карте с помощью d3. Он нуждается в GeoJson для ввода, но это правда, что круги не поддерживаются GeoJson?

4 ответов


когда я смотрю спецификации GeoJson, я вижу, что круги поддерживаются

Это не так. Кажется, вам удалось найти некоторые поддельные или неправильные спецификации. Перейти к geojson.org чтобы найти технические характеристики, нет ничего о кругах.


отсутствие поддержки круга от geojson, но вы можете использовать LineString для имитации круга

использовать geiometry линия объекта

"geometry": {
        "type": "LineString",
        "coordinates": [
                    [center_X, center_y],
                    [center_X, center_y]
                ]
      }
then set the dynamic style use radius as the strokeweight
function featureStyle(feature){
    return {
      strokeWeight: radius,
    };
  }

это похоже на круг на карте.


Как принято отвечать объясняет, круги не поддерживаются в спецификации GeoJson.

большинство реализаций карты, однако, позволят вам создавать круги, но в случае, если это не работает для вас (например. вам нужно сохранить его в базе данных и запросить его), решение заключается в создании полигона, который примерно аппроксимирует круг (представьте полигон с 32+ ребрами).

Я написал что это. Вы можете использовать его как это:

const circleToPolygon = require('circle-to-polygon');

const coordinates = [-27.4575887, -58.99029]; //[lon, lat]
const radius = 100;                           // in meters
const numberOfEdges = 32;                     //optional that defaults to 32

let polygon = circleToPolygon(coordinates, radius, numberOfEdges);

чтобы уточнить, почему круги не поддерживаются, это связано с кривизной Земли. Поскольку земля не является совершенной сферой, если вы нарисуете на ней круглую форму, она также не будет совершенным кругом. Однако приведенное выше решение работает для большинства сценариев, в которых критическая точность не требуется.


A circle... some code I use for making a circle for an OpenStreetMap

-- x is decimal latitude
-- y is decimal longitude
-- r is radius --  .00010 is about 40m in OSM (3 about 50km)

-- Adjust for map latitude distortion further north or south

x = math.log(math.tan((90 + x) * math.pi/360)) / (math.pi/180)

-- For loop to gather all the points of circle here 1 to 360
-- can also use the for loop to make some other interesting shapes

for i = 1, 360 do
    angle = i * math.pi / 180
    ptx = x + r * math.cos( angle )
    pty = y + r * math.sin( angle )

-- readjust latitude for map distortion

    ptx = 180/math.pi * (2 * math.atan(math.exp( ptx * math.pi/180)) - math.pi/2 )

-- Build an array of positions for GeoJSON - formatted lat and long

    data[i] = '[' .. string.format("%.6f",pty) .. ","
    data[i] = data[i] .. string.format("%.6f",ptx) .. ']'

-- End of for loop
end

-- Cycle through the data array with another for loop to build the
   coordinates (put in brackets and commas etc. for the actual
   GeoJSON coordinates string. Add data[1] to the end to close
   the polygon (circle). A circle.

-- If you want a solid circle then use fill and a hex color
-- If you want a LineString just make fill invisible or #ffffff
      Include the stroke-width and stroke-color parameters as well.
-- If latitude is greater than 89.5 or less than -89.5 you may wish
   to cut off the circle by drawing a line at polar regions by using
   those latitudes.
-- I use this simply for several circles and not for hundreds of them.

Cheers!
--