Convert a Google Maps polygon path to an SVG path

前端 未结 2 1174
自闭症患者
自闭症患者 2020-12-18 16:18

When a user has drawn a polygon in Google Maps using the built in Drawing Manager I save the polygon path. I want to convert this polygon path to an SVG path so that I can r

2条回答
  •  無奈伤痛
    2020-12-18 16:52

    You can't use the coordinates directly, you first must translate them to points based on a projection.

    For the mercator-projection you'll find the formula here: https://stackoverflow.com/a/14457180/459897

    A javascript-function based on this formula may look like this:

    /**
      *@param latLng object with properties lat and lng(of the coordinate)
      *@return object with properties x and y(of the translated latLng)
      **/
    function latLng2point(latLng){
    
      return {
              x:(latLng.lng+180)*(256/360),
              y:(256/2)-(256*Math.log(Math.tan((Math.PI/4)
                         +((latLng.lat*Math.PI/180)/2)))/(2*Math.PI))
             };
    }
    

    Convert the coordinates of the path via this function. A path in svg is a sequence of x,y-pairs, delimited by a space as seen in the answer by AniV( but I guess you know what to do with a svg-path).

    When you Convert the path, create 4 variables where you store:

    1. the min-x-value
    2. the max-x-value
    3. the min-y-value
    4. the max-y-value

    These variables use to calculate the viewBox of the svg-element.

    the 4 parameters for the viewBox are:

    1. x: use minX
    2. y: use minY
    3. width: use (maxX-minX)
    4. height: use (maxY-minY)

    Demo(drawing the shape of the US): http://jsfiddle.net/doktormolle/9xhsL39u/

    (Note: the demo loads the maps-API, but only for the purpose of path-decoding, the used paths are very complex and therefore encoded. The maps-API is not required for the coordinate-conversion/svg-drawing)

提交回复
热议问题