我想编写一个应用程序,让用户在GoogleMap上绘制一个多边形,然后让他将其保存到数据库中。
稍后当我们想要时,他应该能够从数据库中在地图上绘制多边形。
这样做的最佳方法是什么?
我建议将多边形数据保存在js数组中,然后使用JSON将其发送到mvc。这是一个好方法吗?
如何在GoogleMap上绘制多边形?
如何使用JS从客户端调用MVC上的控制器?
我是否需要一个特殊的控制器(接收JSON数据)
这是否有任何示例代码?
答案 0 :(得分:2)
这是一个非常粗略的示例,说明如何允许用户绘制多边形。
// 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);
}
尝试here
this也非常有用。
编辑:我应该解释如何绘制多边形......
点击地图会创建一个标记。您可以根据需要创建任意数量的内容。单击已放置的其中一个标记后,将在标记的点之间绘制一个多边形。绘制多边形后,不再计算从中绘制多边形的下一个集合的那些标记。