使用 Google Map API v3 绘制多边形并获取坐标

发布于 2024-10-18 06:14:51 字数 1696 浏览 5 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

怀里藏娇 2024-10-25 06:14:51

使用谷歌提供的 getter 更干净/更安全,而不是像某些人那样访问属性

google.maps.event.addListener(drawingManager, 'overlaycomplete', function(polygon) {
    var coordinatesArray = polygon.overlay.getPath().getArray();
});

It's cleaner/safer to use the getters provided by google instead of accessing the properties like some did

google.maps.event.addListener(drawingManager, 'overlaycomplete', function(polygon) {
    var coordinatesArray = polygon.overlay.getPath().getArray();
});
我也只是我 2024-10-25 06:14:51

如果您需要的只是坐标,这里是我喜欢使用的绘图工具 - 移动多边形或重新塑造它的形状,坐标将显示在地图正下方:jsFiddle 在这里

另外,这里有一个 Codepen

JS

var bermudaTriangle;
function initialize() {
    var myLatLng = new google.maps.LatLng(33.5190755, -111.9253654);
    var mapOptions = {
        zoom: 12,
        center: myLatLng,
        mapTypeId: google.maps.MapTypeId.RoadMap
    };

    var map = new google.maps.Map(document.getElementById('map-canvas'),
                                  mapOptions);


    var triangleCoords = [
        new google.maps.LatLng(33.5362475, -111.9267386),
        new google.maps.LatLng(33.5104882, -111.9627875),
        new google.maps.LatLng(33.5004686, -111.9027061)

    ];

    // Construct the polygon
    bermudaTriangle = new google.maps.Polygon({
        paths: triangleCoords,
        draggable: true,
        editable: true,
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35
    });

    bermudaTriangle.setMap(map);
    google.maps.event.addListener(bermudaTriangle, "dragend", getPolygonCoords);
    google.maps.event.addListener(bermudaTriangle.getPath(), "insert_at", getPolygonCoords);
    google.maps.event.addListener(bermudaTriangle.getPath(), "remove_at", getPolygonCoords);
    google.maps.event.addListener(bermudaTriangle.getPath(), "set_at", getPolygonCoords);
}

function getPolygonCoords() {
    var len = bermudaTriangle.getPath().getLength();
    var htmlStr = "";
    for (var i = 0; i < len; i++) {
        htmlStr += bermudaTriangle.getPath().getAt(i).toUrlValue(5) + "<br>";
    }
    document.getElementById('info').innerHTML = htmlStr;
}

HTML

<body onload="initialize()">
    <h3>Drag or re-shape for coordinates to display below</h3>
    <div id="map-canvas">
    </div>
    <div id="info">
    </div>
</body>

CSS

#map-canvas {
    width: auto;
    height: 350px;
}
#info {
    position: absolute;
    font-family: arial, sans-serif;
    font-size: 18px;
    font-weight: bold;
}

If all you need is the coordinates here is a drawing tool I like to use - move the polygon or re-shape it and the coordinates will display right below the map: jsFiddle here.

Also, here is a Codepen

JS

var bermudaTriangle;
function initialize() {
    var myLatLng = new google.maps.LatLng(33.5190755, -111.9253654);
    var mapOptions = {
        zoom: 12,
        center: myLatLng,
        mapTypeId: google.maps.MapTypeId.RoadMap
    };

    var map = new google.maps.Map(document.getElementById('map-canvas'),
                                  mapOptions);


    var triangleCoords = [
        new google.maps.LatLng(33.5362475, -111.9267386),
        new google.maps.LatLng(33.5104882, -111.9627875),
        new google.maps.LatLng(33.5004686, -111.9027061)

    ];

    // Construct the polygon
    bermudaTriangle = new google.maps.Polygon({
        paths: triangleCoords,
        draggable: true,
        editable: true,
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35
    });

    bermudaTriangle.setMap(map);
    google.maps.event.addListener(bermudaTriangle, "dragend", getPolygonCoords);
    google.maps.event.addListener(bermudaTriangle.getPath(), "insert_at", getPolygonCoords);
    google.maps.event.addListener(bermudaTriangle.getPath(), "remove_at", getPolygonCoords);
    google.maps.event.addListener(bermudaTriangle.getPath(), "set_at", getPolygonCoords);
}

function getPolygonCoords() {
    var len = bermudaTriangle.getPath().getLength();
    var htmlStr = "";
    for (var i = 0; i < len; i++) {
        htmlStr += bermudaTriangle.getPath().getAt(i).toUrlValue(5) + "<br>";
    }
    document.getElementById('info').innerHTML = htmlStr;
}

HTML

<body onload="initialize()">
    <h3>Drag or re-shape for coordinates to display below</h3>
    <div id="map-canvas">
    </div>
    <div id="info">
    </div>
</body>

CSS

#map-canvas {
    width: auto;
    height: 350px;
}
#info {
    position: absolute;
    font-family: arial, sans-serif;
    font-size: 18px;
    font-weight: bold;
}
烂柯人 2024-10-25 06:14:51

的示例

这里有上面使用 API V3 http://nettique.free.fr/gmap/toolbar.html

here you have the example above using API V3

http://nettique.free.fr/gmap/toolbar.html

漫漫岁月 2024-10-25 06:14:51

好吧,不幸的是,如果一个人是匿名/未登录的话,似乎无法直接从maps.google.com放置自定义标记并绘制(并获取坐标)(如果我没记错的话,几年前这是可能的)。尽管如此,感谢这里的答案,我设法制作了一个示例组合,其中既有 Google Places 搜索,也允许通过绘图库进行绘图,并在选择任何类型的形状(包括多边形的坐标)时转储坐标可以复制粘贴;代码在这里:

如下所示:

 test.png

(地点标记是单独处理的,可以通过搜索输入表单元素的 DEL“按钮”删除;“curpos”显示地图视口的当前中心[位置]和缩放级别)。

Well, unfortunately it seems that one cannot place custom markers and draw (and obtain coordinates) directly from maps.google.com if one is anonymous/not logged in (as it was possible some years ago, if I recall correctly). Still, thanks to the answers here, I managed to make a combination of examples that has both the Google Places search, and allows drawing via the drawing library, and dumps coordinates upon making a selection of any type of shape (including coordinates for polygon) that can be copypasted; the code is here:

This is how it looks like:

test.png

(The Places markers are handled separately, and can be deleted via the DEL "button" by the search input form element; "curpos" shows the current center [position] and zoom level of the map viewport).

我一直都在从未离去 2024-10-25 06:14:51

由于 Google 有时会更新固定对象属性的名称,因此最佳实践是使用 GMaps V3 方法来获取坐标 event.overlay.getPath().getArray() 并获取纬度 latlng。 lat() 和 lng latlng.lng()

所以,我只是想改进这个答案,以多边形和 POSTGIS 插入案例场景为例:

google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
    var str_input ='POLYGON((';
    if (event.type == google.maps.drawing.OverlayType.POLYGON) {
      console.log('polygon path array', event.overlay.getPath().getArray());
      $.each(event.overlay.getPath().getArray(), function(key, latlng){
        var lat = latlng.lat();
        var lon = latlng.lng();
        console.log(lat, lon); 
        str_input += lat +' '+ lon +',';
      });
    }
    str_input = str_input.substr(0,str_input.length-1) + '))';
    console.log('the str_input will be:', str_input);

    // YOU CAN THEN USE THE str_inputs AS IN THIS EXAMPLE OF POSTGIS POLYGON INSERT
    // INSERT INTO your_table (the_geom, name) VALUES (ST_GeomFromText(str_input, 4326), 'Test')

  });

Since Google updates sometimes the name of fixed object properties, the best practice is to use GMaps V3 methods to get coordinates event.overlay.getPath().getArray() and to get lat latlng.lat() and lng latlng.lng().

So, I just wanted to improve this answer a bit exemplifying with polygon and POSTGIS insert case scenario:

google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
    var str_input ='POLYGON((';
    if (event.type == google.maps.drawing.OverlayType.POLYGON) {
      console.log('polygon path array', event.overlay.getPath().getArray());
      $.each(event.overlay.getPath().getArray(), function(key, latlng){
        var lat = latlng.lat();
        var lon = latlng.lng();
        console.log(lat, lon); 
        str_input += lat +' '+ lon +',';
      });
    }
    str_input = str_input.substr(0,str_input.length-1) + '))';
    console.log('the str_input will be:', str_input);

    // YOU CAN THEN USE THE str_inputs AS IN THIS EXAMPLE OF POSTGIS POLYGON INSERT
    // INSERT INTO your_table (the_geom, name) VALUES (ST_GeomFromText(str_input, 4326), 'Test')

  });
谁把谁当真 2024-10-25 06:14:51

为了完成你想要的,你必须从多边形中获取路径。路径将是 LatLng 点的数组。您获取数组的元素,并使用下面函数中的方法 .lat 和 .lng 分割 LatLng 对,我有一个与标记多边形周围的折线相对应的冗余数组。

储蓄是另一回事。然后您可以选择多种方法。您可以将点列表保存为 csv 格式的字符串并将其导出到文件(迄今为止最简单的解决方案)。我强烈推荐 GPS TXT 格式,例如 GPS TRACKMAKER(很棒的免费版本软件)可以读取的格式(有 2 个)。如果您有能力将它们保存到数据库中,那么这是一个很好的解决方案(为了冗余,我两者都做)。

function areaPerimeterParse(areaPerimeterPath) {
    var flag1stLoop = true;
    var areaPerimeterPathArray = areaPerimeterPath.getPath();
    var markerListParsedTXT = "Datum,WGS84,WGS84,0,0,0,0,0\r\n";

    var counter01 = 0;
    var jSpy = "";
    for (var j = 0;j<areaPerimeterPathArray.length;j++) {
        counter01++;
        jSpy += j+"  ";
        if (flag1stLoop) {
            markerListParsedTXT += 'TP,D,'+[ areaPerimeterPathArray.getAt(j).lat(), areaPerimeterPathArray.getAt(j).lng()].join(',')+',00/00/00,00:00:00,1'+'\r\n';
            flag1stLoop = false;
        } else {
            markerListParsedTXT += 'TP,D,'+[ areaPerimeterPathArray.getAt(j).lat(), areaPerimeterPathArray.getAt(j).lng()].join(',')+',00/00/00,00:00:00,0'+'\r\n';
        }

    }
    // last point repeats first point
    markerListParsedTXT += 'TP,D,'+[ areaPerimeterPathArray.getAt(0).lat(), areaPerimeterPathArray.getAt(0).lng()].join(',')+',00/00/00,00:00:00,0'+'\r\n';
    return markerListParsedTXT;
}

注意,以“,1”(而不是“,0”)结尾的行开始一个新的多边形(此格式允许您在同一文件中保存多个多边形)。我发现 TXT 比基于 XML 的格式 GPX 和 KML 更容易阅读。

to accomplish what you want, you must getPaths from the polygon. Paths will be an array of LatLng points. you get the elements of the array and split the LatLng pairs with the methods .lat and .lng in the function below, i have a redundant array corresponding to a polyline that marks the perimeter around the polygon.

saving is another story. you can then opt for many methods. you may save your list of points as a csv formatted string and export that to a file (easiest solution, by far). i highly recommend GPS TXT formats, like the ones (there are 2) readable by GPS TRACKMAKER (great free version software). if you are competent to save them to a database, that is a great solution (i do both, for redundancy).

function areaPerimeterParse(areaPerimeterPath) {
    var flag1stLoop = true;
    var areaPerimeterPathArray = areaPerimeterPath.getPath();
    var markerListParsedTXT = "Datum,WGS84,WGS84,0,0,0,0,0\r\n";

    var counter01 = 0;
    var jSpy = "";
    for (var j = 0;j<areaPerimeterPathArray.length;j++) {
        counter01++;
        jSpy += j+"  ";
        if (flag1stLoop) {
            markerListParsedTXT += 'TP,D,'+[ areaPerimeterPathArray.getAt(j).lat(), areaPerimeterPathArray.getAt(j).lng()].join(',')+',00/00/00,00:00:00,1'+'\r\n';
            flag1stLoop = false;
        } else {
            markerListParsedTXT += 'TP,D,'+[ areaPerimeterPathArray.getAt(j).lat(), areaPerimeterPathArray.getAt(j).lng()].join(',')+',00/00/00,00:00:00,0'+'\r\n';
        }

    }
    // last point repeats first point
    markerListParsedTXT += 'TP,D,'+[ areaPerimeterPathArray.getAt(0).lat(), areaPerimeterPathArray.getAt(0).lng()].join(',')+',00/00/00,00:00:00,0'+'\r\n';
    return markerListParsedTXT;
}

attention, the line that ends with ",1" (as opposed to ",0") starts a new polygon (this format allows you to save multiple polygons in the same file). i find TXT more human readable than the XML based formats GPX and KML.

纸伞微斜 2024-10-25 06:14:51

其他答案显示您创建多边形,但不显示如何获取坐标...

我不确定最好的方法,但这是一种方法..似乎应该有一种方法来获取路径从多边形,但我找不到一个,并且 getPath() 似乎对我不起作用。所以这里有一个对我有用的手动方法。

一旦你完成了多边形的绘制,并将多边形传递给覆盖完成函数,你就可以在 Polygon.overlay.latLngs.b[0].b 中找到坐标

google.maps.event.addListener(drawingManager, 'overlaycomplete', function(polygon) {
        $.each(polygon.overlay.latLngs.b[0].b, function(key, latlng){
            var lat = latlng.d;
            var lon = latlng.e;
            console.log(lat, lon); //do something with the coordinates
        });
});

请注意,我使用 jquery 来循环坐标列表,但是您可以执行循环。

The other answers show you to create the polygons, but not how to get the coordinates...

I'm not sure the best way to do it, but heres one way.. It seems like there should be a method to get the paths from the polygon, but I can't find one, and getPath() doesn't seem to work for me. So here's a manual approach that worked for me..

Once you've finished drawing your polygon, and pass in your polygon to the overlay complete function, you can find the coordinates in the polygon.overlay.latLngs.b[0].b

google.maps.event.addListener(drawingManager, 'overlaycomplete', function(polygon) {
        $.each(polygon.overlay.latLngs.b[0].b, function(key, latlng){
            var lat = latlng.d;
            var lon = latlng.e;
            console.log(lat, lon); //do something with the coordinates
        });
});

note, i'm using jquery to loop over the list of coordinates, but you can do loop however.

酷遇一生 2024-10-25 06:14:51

添加到 Gisheri 的答案

以下代码对我有用

 var drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.MARKER,
    drawingControl: true,
    drawingControlOptions: {
      position: google.maps.ControlPosition.TOP_CENTER,
      drawingModes: [
        google.maps.drawing.OverlayType.POLYGON
      ]
    },
    markerOptions: {
      icon: 'images/beachflag.png'
    },
    circleOptions: {
      fillColor: '#ffff00',
      fillOpacity: 1,
      strokeWeight: 5,
      clickable: false,
      editable: true,
      zIndex: 1
    }

  });

  google.maps.event.addListener(drawingManager, 'overlaycomplete', function(polygon) {
      //console.log(polygon.overlay.latLngs.j[0].j);return false;
        $.each(polygon.overlay.latLngs.j[0].j, function(key, LatLongsObject){
            var LatLongs    =   LatLongsObject;

            var lat = LatLongs.k;
            var lon = LatLongs.B;
           console.log("Lat is: "+lat+" Long is: "+lon); //do something with the coordinates

        });

Adding to Gisheri's answer

Following code worked for me

 var drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.MARKER,
    drawingControl: true,
    drawingControlOptions: {
      position: google.maps.ControlPosition.TOP_CENTER,
      drawingModes: [
        google.maps.drawing.OverlayType.POLYGON
      ]
    },
    markerOptions: {
      icon: 'images/beachflag.png'
    },
    circleOptions: {
      fillColor: '#ffff00',
      fillOpacity: 1,
      strokeWeight: 5,
      clickable: false,
      editable: true,
      zIndex: 1
    }

  });

  google.maps.event.addListener(drawingManager, 'overlaycomplete', function(polygon) {
      //console.log(polygon.overlay.latLngs.j[0].j);return false;
        $.each(polygon.overlay.latLngs.j[0].j, function(key, LatLongsObject){
            var LatLongs    =   LatLongsObject;

            var lat = LatLongs.k;
            var lon = LatLongs.B;
           console.log("Lat is: "+lat+" Long is: "+lon); //do something with the coordinates

        });
故人如初 2024-10-25 06:14:51

清理了 chuycepeda 的内容并将其放入文本区域中以表格形式发回。

google.maps.event.addListener(drawingManager, 'overlaycomplete', function (event) {
    var str_input = '{';
    if (event.type == google.maps.drawing.OverlayType.POLYGON) {
        $.each(event.overlay.getPath().getArray(), function (key, latlng) {
            var lat = latlng.lat();
            var lon = latlng.lng();
            str_input += lat + ', ' + lon + ',';
        });
    }
    str_input = str_input.substr(0, str_input.length - 1) + '}';

    $('textarea#Geofence').val(str_input);
});

Cleaned up what chuycepeda has and put it into a textarea to send back in a form.

google.maps.event.addListener(drawingManager, 'overlaycomplete', function (event) {
    var str_input = '{';
    if (event.type == google.maps.drawing.OverlayType.POLYGON) {
        $.each(event.overlay.getPath().getArray(), function (key, latlng) {
            var lat = latlng.lat();
            var lon = latlng.lng();
            str_input += lat + ', ' + lon + ',';
        });
    }
    str_input = str_input.substr(0, str_input.length - 1) + '}';

    $('textarea#Geofence').val(str_input);
});
寂寞陪衬 2024-10-25 06:14:51

试试这个

在你的控制器中使用

> $scope.onMapOverlayCompleted = onMapOverlayCompleted;
> 
>  function onMapOverlayCompleted(e) {
> 
>                 e.overlay.getPath().getArray().forEach(function (position) {
>                     console.log('lat', position.lat());
>                     console.log('lng', position.lng());
>                 });
> 
>  }

**In Your html page , include drawning manaer** 


    <ng-map id="geofence-map" zoom="8" center="current" default-style="true" class="map-layout map-area"
                        tilt="45"
                        heading="90">

                    <drawing-manager
                            on-overlaycomplete="onMapOverlayCompleted()"
                            drawing-control-options="{position: 'TOP_CENTER',drawingModes:['polygon','circle']}"
                            drawingControl="true"
                            drawingMode="null"
                            markerOptions="{icon:'www.example.com/icon'}"
                            rectangleOptions="{fillColor:'#B43115'}"
                            circleOptions="{fillColor: '#F05635',fillOpacity: 0.50,strokeWeight: 5,clickable: false,zIndex: 1,editable: true}">
                    </drawing-manager>
    </ng-map>

try this

In your controller use

> $scope.onMapOverlayCompleted = onMapOverlayCompleted;
> 
>  function onMapOverlayCompleted(e) {
> 
>                 e.overlay.getPath().getArray().forEach(function (position) {
>                     console.log('lat', position.lat());
>                     console.log('lng', position.lng());
>                 });
> 
>  }

**In Your html page , include drawning manaer** 


    <ng-map id="geofence-map" zoom="8" center="current" default-style="true" class="map-layout map-area"
                        tilt="45"
                        heading="90">

                    <drawing-manager
                            on-overlaycomplete="onMapOverlayCompleted()"
                            drawing-control-options="{position: 'TOP_CENTER',drawingModes:['polygon','circle']}"
                            drawingControl="true"
                            drawingMode="null"
                            markerOptions="{icon:'www.example.com/icon'}"
                            rectangleOptions="{fillColor:'#B43115'}"
                            circleOptions="{fillColor: '#F05635',fillOpacity: 0.50,strokeWeight: 5,clickable: false,zIndex: 1,editable: true}">
                    </drawing-manager>
    </ng-map>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文