在谷歌地图上创建一个多边形,并使用MVC将结果保存到数据库中

Creating a polygon on googlemap and save the result to database using MVC

本文关键字:MVC 结果 保存 数据库 创建 谷歌地图 多边形 一个      更新时间:2023-09-26

我想编写一个应用程序,让用户在Google地图上绘制一个多边形,然后让他将其保存到数据库中。

稍后当我们想要时,他应该能够从数据库中在地图上绘制多边形。

最好的方法是什么?

我的建议是将多边形数据保存在 js 数组中,并使用 JSON 将其发送到 mvc。这是一个好方法吗?

如何在谷歌地图上绘制多边形?

如何使用JS从客户端调用MVC上的控制器?

我是否需要为此使用特殊的控制器(接收 JSON 数据)

是否有任何示例代码?

这是一个非常粗略的示例,说明如何允许用户绘制多边形。

  // declare map outside of initialize function so that drawPoints() can use it
  var map;
  // called when page is loaded
  function initialize() {
    // arbitrary point
    var myLatLng = new google.maps.LatLng(24.88484848484, -70.268858484);
    // options to init map with, again arbitrary
    var myOptions = {
      zoom: 5,
      center: myLatLng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    // get our map object
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    // array to store markers that user has drawn
    var markers = [];
    // add event listener to the map to get the click events and draw a marker
    google.maps.event.addListener(map, 'click', function(e) {
      var marker = new google.maps.Marker();
      marker.setPosition(e.latLng);
      marker.setMap(map);
      marker.setVisible(true);
      // push it to the markers array
      markers.push(marker);
      // add an event listener to each marker so that we can draw a polygon
      // once user clicks on on of the markers in the markers array, assuming
      // that they are ready to join up the polygon and have it drawn
      google.maps.event.addListener(marker, 'click', function(e) {
        drawPoints(markers);
        // empty the markers array so that the user can draw a new one, without
        // them all joining up. this is perphaps where you would want to push
        // the markers array to a database, storing the points as latitude/longitude
        // values so that they can be retrieved, put into an array, and drawn
        // as a polygon again. 
        markers = [];
      });
    });
  }
  function drawPoints(markers) {
    var poly = new google.maps.Polygon;
    var points = [];
    for (var i = 0; i < markers.length; i++) {
      points.push(markers[i].getPosition());
    }
    poly.setMap(map);
    poly.setPath(points);
    poly.setVisible(true);
  }​

在这里尝试一下

这也将非常有用。

编辑:我可能应该解释如何绘制多边形...

单击地图将创建一个标记。您可以根据需要创建任意数量。单击已放置的标记之一后,将在标记的点之间绘制一个多边形。绘制面后,这些标记将不再计入从中绘制面的下一组。