save google map polygon to postgreSQL database

故事扮演 提交于 2019-12-08 06:38:25

问题


I develop a web-based application where a user will create a polygon on a map and the database will return points of interest.

The problem is that the postgreSQL saves the polygon in a different way than google map polygon.

So how I can save the user polygon to postgis?

I already use google maps v3 api and geojson


回答1:


Some code would be useful. In the absence of that here's a best guess generic answer: In general terms you will need to work out how to map (convert) each format to the other. Then you can convert to the format suitable for the database before you save and convert from database format to google maps format when you retrieve. I imagine each polygon is a set of latitude/longitude pairs in both formats so it shouldn't be too difficult.

Alternatively, since you're using JSON, you could just save the JSON to a text field in the database (or to a JSON field in the upcoming 9.2 release of PostgreSQL):

http://www.postgresql.org/docs/9.2/static/datatype-json.html

However if you would like to perform geographical queries in the database that would obviously limit your options.




回答2:


In my js file i create a shape which is polygon

shape = new google.maps.Polygon({
 Editable:true,
 strokeColor: 'FF0000',
 strokeOpacity: 0.8,
 strokeWeight: 1,
 fillColor: 'FF0000',
 fillOpacity: 0.4
});

Then I create the function addPoint

function addPoint(e) {
 shape.setMap(map);
 vertices= shape.getPath();
 vertices.push(e.latLng);
 polygon.push(e.latLng);
}

I pass the addPoint function to map object

map = new google.maps.Map(document.getElementById("map"), mapOptions);
google.maps.event.addListener(map,'click',addPoint);

In my html I have the button with id=polygon. I convert the coordinates in postgres format (long,lat)

$("#polygon").click(function(e){
 a=JSON.stringify(polygon);
 var c=JSON.parse(a);
 console.info(c);
 vertices.forEach(function(xy, i) {
  x.push(xy.lng()+" "+xy.lat());
 });
 shape.setMap(map);

The variable which contains the polygon is the array which I called it x the I have an ajax call to pass polygon array x to my model

$.ajax({
 url: 'myurl',
 type: 'post',
 data: {'polygon':x},
 datatype: 'json',
 success: function(data) {
 console.info(data)
 }
});

In my model (Codeigniter) I convert the polygon (lat,long) to postgres polygon (long,lat)

public function getPolygon($polygon){
 header('Content-type: application/json');
 $upolygon="";

$length=count($polygon);
for ($i=0;$i<$length;$i++){
 $upolygon.=$polygon[$i].' ,';
}
$upolygon.=$polygon[0];
$query = "some query with the formated polygon";
foreach ($query->result() as $row)
 {
  $data[]= array("some data");
 }
 echo json_encode($data);
}


来源:https://stackoverflow.com/questions/12204417/save-google-map-polygon-to-postgresql-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!