如何将谷歌地图覆盖层形状保存到数据库中?

17

我想把谷歌地图叠加形状保存到数据库中。这是我的代码。它完美地运行,但我只需要把all_shapes数组保存在数据库中。

<html>
<head>

<style type="text/css">
  #map, html, body
  {
      padding: 0;
      margin: 0;
      height: 100%;
  }
</style>

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&libraries=drawing,geometry"></script>

<script>
var coordinates = [];
var all_shapes = [];

var selectedShape;
</script>

<script>
function draw_shape()
{
    for(var i = 0; i < all_shapes.length; i++)
    {
        all_shapes[i].setMap(null);
    }

    for(var i = 0; i < all_shapes.length; i++)
    {
        all_shapes[i].setMap(map);
    }
}
</script>

<script>
function clearSelection()
{
    if(selectedShape)
    {
        selectedShape.setEditable(false);
        selectedShape = null;
    }
}

function setSelection(shape)
{
    clearSelection();
    selectedShape = shape;
    shape.setEditable(true);
}

function deleteSelectedShape()
{
    if (selectedShape)
    {
        selectedShape.setMap(null);
    }
}
</script>

<script>
function save_coordinates_to_array(newShapeArg)
{
    if(newShapeArg.type == google.maps.drawing.OverlayType.POLYGON)
    {
        var polygonBounds = newShapeArg.getPath();

        for(var i = 0 ; i < polygonBounds.length ; i++)
        {
            coordinates.push(polygonBounds.getAt(i).lat(), polygonBounds.getAt(i).lng());
        }
    }
    else
    {
        //alert("Not polygon");/////////////
    }   
}
</script>

<script>
var map;

function initialize()
{
    map = new google.maps.Map(document.getElementById('map'), {zoom: 12, center: new google.maps.LatLng(32.344, 51.048)});

    var drawingManager = new google.maps.drawing.DrawingManager();
    drawingManager.setMap(map);

    google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
        var newShape = e.overlay;
        newShape.type = e.type;

        all_shapes.push(newShape);

        setSelection(newShape);

        save_coordinates_to_array(newShape);

        google.maps.event.addListener(newShape, 'click', function() {setSelection(newShape)});
      });

    google.maps.event.addListener(map, 'click', function(e) {clearSelection();});
}

google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>

<body>
<table border="1">
  <tr>
    <td>Name</td>
    <td><input name="name" id="name" type="text"></td>
  </tr>
  <tr>
    <td>Color</td>
    <td>
      <table border="1" width="100%">
        <tr>
          <td bgcolor="#FF0000">&nbsp;</td>
          <td bgcolor="#00FF00">&nbsp;</td>
          <td bgcolor="#0000FF">&nbsp;</td>
        </tr>
      </table>
    </td>
  </tr>
  <tr>
    <td colspan="2"><input name="save" type="button" value="Save" onClick="draw_shape()"></td>
  </tr>
  <tr>
    <td colspan="2"><input name="delete" type="button" value="Delete" onClick="deleteSelectedShape()"></td>
  </tr>  
</table>

<div id="map"></div>
</body>

</html>

我应该在哪里以及如何将创建的覆盖层存储到数据库中。所有形状都保存在var all_shapes = [];数组中。我在数据库字段中应该选择哪种类型? 我是指例如int,char等。

我打算使用MySQL和PHP。


我遇到了一个相同的问题,即如何将谷歌地图上的多边形保存到PostgreSQL数据库中。以下是我所做的:https://stackoverflow.com/a/39438476/924300 - Dimitris Kougioumtzis
4个回答

37
当您只想以某种方式存储形状时,可以使用JSON字符串,将其存储在例如Text列中(char太小无法存储详细的多边形/折线)。
注意:创建JSON字符串时,必须转换属性(例如到本机数组或对象),不能直接存储例如LatLng,因为原型将在保存时丢失。多边形/折线的路径可以存储encoded
另一种方法: 使用多个列,例如
  1. 一个列(varchar),其中存储类型(LatLng、Circle、Polyline等)
  2. 一个列(geometry),其中存储几何特征(LatLng、Polygon或Polyline)
  3. 一个列(int),其中存储半径(插入圆形时使用)
  4. 可选列(text),其中存储样式选项(如果需要)
第一个建议足以简单存储。
当您需要选择特定形状时,例如给定区域,使用第二个建议。 有关空间扩展的详细信息,请参见http://dev.mysql.com/doc/refman/5.0/en/spatial-extensions.html

这两个函数可以去除循环引用并创建可存储对象,或从这些存储的对象中恢复叠加层。

var IO={
  //returns array with storable google.maps.Overlay-definitions
  IN:function(arr,//array with google.maps.Overlays
              encoded//boolean indicating if pathes should be stored encoded
              ){
      var shapes     = [],
          goo=google.maps,
          shape,tmp;

      for(var i = 0; i < arr.length; i++)
      {   
        shape=arr[i];
        tmp={type:this.t_(shape.type),id:shape.id||null};


        switch(tmp.type){
           case 'CIRCLE':
              tmp.radius=shape.getRadius();
              tmp.geometry=this.p_(shape.getCenter());
            break;
           case 'MARKER': 
              tmp.geometry=this.p_(shape.getPosition());   
            break;  
           case 'RECTANGLE': 
              tmp.geometry=this.b_(shape.getBounds()); 
             break;   
           case 'POLYLINE': 
              tmp.geometry=this.l_(shape.getPath(),encoded);
             break;   
           case 'POLYGON': 
              tmp.geometry=this.m_(shape.getPaths(),encoded);

             break;   
       }
       shapes.push(tmp);
    }

    return shapes;
  },
  //returns array with google.maps.Overlays
  OUT:function(arr,//array containg the stored shape-definitions
               map//map where to draw the shapes
               ){
      var shapes     = [],
          goo=google.maps,
          map=map||null,
          shape,tmp;

      for(var i = 0; i < arr.length; i++)
      {   
        shape=arr[i];       

        switch(shape.type){
           case 'CIRCLE':
             tmp=new goo.Circle({radius:Number(shape.radius),
                                  center:this.pp_.apply(this,shape.geometry)});
            break;
           case 'MARKER': 
             tmp=new goo.Marker({position:this.pp_.apply(this,shape.geometry)});
            break;  
           case 'RECTANGLE': 
             tmp=new goo.Rectangle({bounds:this.bb_.apply(this,shape.geometry)});
             break;   
           case 'POLYLINE': 
             tmp=new goo.Polyline({path:this.ll_(shape.geometry)});
             break;   
           case 'POLYGON': 
             tmp=new goo.Polygon({paths:this.mm_(shape.geometry)});

             break;   
       }
       tmp.setValues({map:map,id:shape.id})
       shapes.push(tmp);
    }
    return shapes;
  },
  l_:function(path,e){
    path=(path.getArray)?path.getArray():path;
    if(e){
      return google.maps.geometry.encoding.encodePath(path);
    }else{
      var r=[];
      for(var i=0;i<path.length;++i){
        r.push(this.p_(path[i]));
      }
      return r;
    }
  },
  ll_:function(path){
    if(typeof path==='string'){
      return google.maps.geometry.encoding.decodePath(path);
    }
    else{
      var r=[];
      for(var i=0;i<path.length;++i){
        r.push(this.pp_.apply(this,path[i]));
      }
      return r;
    }
  },

  m_:function(paths,e){
    var r=[];
    paths=(paths.getArray)?paths.getArray():paths;
    for(var i=0;i<paths.length;++i){
        r.push(this.l_(paths[i],e));
      }
     return r;
  },
  mm_:function(paths){
    var r=[];
    for(var i=0;i<paths.length;++i){
        r.push(this.ll_.call(this,paths[i]));

      }
     return r;
  },
  p_:function(latLng){
    return([latLng.lat(),latLng.lng()]);
  },
  pp_:function(lat,lng){
    return new google.maps.LatLng(lat,lng);
  },
  b_:function(bounds){
    return([this.p_(bounds.getSouthWest()),
            this.p_(bounds.getNorthEast())]);
  },
  bb_:function(sw,ne){
    return new google.maps.LatLngBounds(this.pp_.apply(this,sw),
                                        this.pp_.apply(this,ne));
  },
  t_:function(s){
    var t=['CIRCLE','MARKER','RECTANGLE','POLYLINE','POLYGON'];
    for(var i=0;i<t.length;++i){
       if(s===google.maps.drawing.OverlayType[t[i]]){
         return t[i];
       }
    }
  }

}
< p > IO.IN 返回的数组可以发送到服务器端脚本。 服务器端脚本应迭代此数组并将 JSON 字符串插入表中:

<?php
$mysqli = new mysqli(/*args*/);
$stmt = $mysqli->prepare('INSERT INTO `tableName`(`columnName`) VALUES (?)');
$stmt->bind_param('s', $json);

foreach($_POST['shapes'] as $value){
  $json = json_encode($value);
  $stmt->execute();
}
?>

恢复形状,请获取它们:

<?php
$json=array();
$res=$mysqli->query('SELECT `columnName` from `tableName`');
while ($row = $res->fetch_assoc()) {
        $json[]=json_decode($row['columnName']);
    }
$res->close();
$json=json_encode($json);
?>

并将结果传递给 IO.OUT()
IO.OUT(<?php echo $json;?>, someGoogleMapsInstance);

演示:http://jsfiddle.net/doktormolle/EdZk4/show/


我对使用JSON方法很感兴趣,但存在循环引用问题。通过使用JSON,我们只需要包含一个字符串的列。是否有可能使用JSON呢? - Sponge Bob
关于使用您的第二种方法来使用一些列。要保存多边形的所有点,我应该如何保存它?我的意思是我必须使用一个字符串列还是很多整数列? - Sponge Bob
1
我已经添加了一些关于第一个方法的细节。第二种方法要复杂得多,我不确定在接下来的几天里是否有时间进行详细说明。但是为了回答与列类型相关的问题:它是GEOMETRY,此类型可用于存储点、线和多边形,足以存储任何类型的google.maps.Overlay(除了CIRCLE,这里需要额外的列来存储半径)。 - Dr.Molle
1
你的JSON方法非常完美!非常感谢! - pmrotule
@Dr.Molle,你能否给我一些建议关于在sqlite数据库中保存经纬度点的问题。我正在开发一个跑步跟踪应用程序,现在我想知道是否应该将每个点保存为单独的行,还是将所有点收集到一个数组中并存储该数组?有什么想法吗? - alex
显示剩余2条评论

5
Simple GeoJson Editor 是在谷歌地图上绘制、编辑、删除和保存形状为GeoJson的示例。该项目作者是一名谷歌实习生,他在这篇文章中描述了该项目。
其中JavascriptHTML没有被压缩。
还有一个更好的开源工具可以在Geojson.io找到。

1
我发现代码中有奇怪的行为:http://jsfiddle.net/doktormolle/EdZk4/show/
我在IN函数中添加了下面的代码:
         if (tmp.type != 'MARKER') {
             tmp.strokeColor = shape.strokeColor;
             tmp.strokeWeight = shape.strokeWeight;
             tmp.fillColor = shape.fillColor;
             tmp.fillOpacity = shape.fillOpacity;
             tmp.editable = shape.getEditable();
             if (tmp.type == 'POLYLINE' || tmp.type == 'POLYGON')
                 tmp.infoWindowContent = shape.infoWindow.content;
         }

所有形状都是可编辑的,但只有最后一个显示为可编辑。例如,我添加了一个可编辑的折线,它在结果中是可编辑的。

    "[{"type":"POLYLINE","id":null,"draggable":false,"geometry":["gn_sFwt`eEvmd@ig|B"],
"strokeColor":"red","strokeWeight":3,"fillOpacity":0.35,"editable":true,
"infoWindowContent":"Polyline Length: 58.80  kms"}]"

我添加了第二个可编辑的折线,但结果是第一个不可编辑,第二个可编辑。
    "[{"type":"POLYLINE","id":null,"draggable":false,"geometry":["gn_sFwt`eEvmd@ig|B"],
"strokeColor":"red","strokeWeight":3,"fillOpacity":0.35,"editable":false,
"infoWindowContent":"Polyline Length: 58.80  kms"},
    {"type":"POLYLINE","id":null,"draggable":false,"geometry":["qoiqFgvheEcsw@ygz@"],
"strokeColor":"red","strokeWeight":3,"fillOpacity":0.35,"editable":true,
"infoWindowContent":"Polyline Length: 41.41  kms"}]"

0
如果您需要存储路径以便稍后在地图上还原它,您也可以使用 Google Maps 编码实用工具。它不像 Dr.Molle 的答案那样强大,但对于存储多边形和折线非常有用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接