save google map polygon to postgreSQL database - google-maps

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

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.

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);
}

Related

Loading geoJSON to Cesium does not work but I get no errors

I try to pass data from PostGIS to Cesium, I believe the simpler way is to use GeoJSON.
To test it I do a query to my PostGIS to get some geoJSON data
SELECT ST_AsGeoJSON(mygeom)
FROM mytable where id = 370;
then I copy the result to a cesium sandcastle to see how it works
var viewer = new Cesium.Viewer('cesiumContainer');
const greenPolygon = viewer.entities.add({
name: "Green extruded polygon",
polygon: {
hierarchy : Cesium.GeoJsonDataSource.load({"type":"MultiPolygon","coordinates":[[[[386788.842267334,4204512.29371444],[386804.47751787,4204512.29371444],[386804.47751787,4204510.66293459],[386788.854170836,4204510.66293459],[386788.842267334,4204512.29371444]]]]}),
extrudedHeight: 100000.0,
material: Cesium.Color.YELLOW.withAlpha(0.5),
outline : true,
outlineColor : Cesium.Color.BLACK,
closeTop: true,
closeBottom: true
},
});
viewer.zoomTo(viewer.entities);
I get no errors in the cesium sandcastle console, but I also see no polygon on the map. The geometry in my PostGIS table is geometry(MultiPolygon,2100), I dont know if this is the issue.
Please advice
Thanks
CesiumJS will not understand your coordinates(ex 386788.842267334,4204512.29371444) defined in your custom spatial reference system.
You must specify coordinates using geographic latitude, and longitude.

Custom Google Maps Layer for Markers and Polygons?

I have a question about the googleMaps Javascript API. Is it possible to create a custom Layer that you can show/hide like the given layers such as traffic and bicycle layer?
I would like to have a own Layer for my Markers and another Layer for polygons.
thanks in advance
I understood of your question that you would like to create a custom layer on your web site. You also need to change the layer informations at any time.
Google maps api provides KML and GeoRSS data formats for "displaying geographic information".
We are going to introduce KML format.
You may create a KML file witch provides the informations for your layer. You can find an example of KML file here. Of course, you can edit this file any time on your server.
This is an example of editing a file on php:
$file = file_get_contents($_SERVER['DOCUMENT_ROOT']."/yourKLMFile.txt");
$file= str_replace("OldValue", "NewValue", $file);
echo ($file);
You also can provide personal data for your users or simply update your layer.
Next, JS.
Google maps api provides the KmlLayer() constructor witch creates your layers and display it on the map (since you have created it).
The constructor takes two important parameters:
The URL of your KML file (probably on your server);
The map in witch you want to display the layer.
This is a sample example:
var ctaLayer = new google.maps.KmlLayer({
url: 'http://googlemaps.github.io/js-v2-samples/ggeoxml/cta.kml',
map: map
});
This is a sample code spinnet wich resume all this:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {lat: 41.876, lng: -87.624}
});
var ctaLayer = new google.maps.KmlLayer({
url: 'http://googlemaps.github.io/js-v2-samples/ggeoxml/cta.kml',
map: map
});
}
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
Remember that you can always update your data file in php.
You may consult the documentation about KML layer and generally google maps' layers on google maps web site.
Tell me a comment if you have some questions

Database instead of kml file

I wonder, is it possible to connect a db to google maps api to render polygons, points etc?
If a store all kml coordinates connected to polygons, will it be possible to render it fra database or do i need to create a kml file to visualize it?
Is there any example?
Thanks!
A KML file is not required to visualize points, polygons, etc using Google Maps API. However, the KML layer is a useful way to represent complex geospatial features.
A backend database with HTTP access could return a list of map coordinates that your client code can render into appropriate shapes using Google Maps API.
The Google Maps API provides examples to create various shapes.
Example to create simple point marker:
https://developers.google.com/maps/documentation/javascript/examples/marker-simple
Example to create simple polygon:
https://developers.google.com/maps/documentation/javascript/examples/polygon-simple
The client code will need to query the data from the database such as from a servlet with access to the database. Database will most likely be running on a different port or from a different server so javascript won't be able to access it directly.
Your server-side component could query a database and return formatted KML or it could return a JSON result that your client code would render. Depends on whether you want to write more backend server code or JavaScript code on the client.
hmmm... I am using another solution now (data from DB to show on Google earth which is default application for KML file) and hope this help :
( may refer to https://sites.google.com/site/canadadennischen888/home/kml/auto-refresh-3d-tracking )(plus, in my other page, there is sample java code)
Details as :
prepare a RestFul service to generate KML file from DB (KML sample as inside above link)
My other jsp code will generate a KMZ file which has a link to my Restful service. KMZ file has onInterval ( as in the bottom)
Jsp web page allow user to download KMZ file.
When Google Earth open KMZ file, Google Earth will auto refresh to get new data from that Restful service
Everytime refreshing, server will send the latest update KML data with new data to GE.
KMZ sample:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2"
xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<NetworkLink>
<name>Dennis_Chen_Canada#Hotmail.com</name>
<open>1</open>
<Link>
<href>http://localhost:9080/google-earth-project/rest/kml/10001/20002</href>
<refreshMode>onInterval</refreshMode>
</Link>
</NetworkLink>
</kml>
result as :
Thanks for you're answer. I don't know if i get somewhat wiser of this, but at least i know that it is possible.
I have used Shape2Sql to save the coordinates in the database.
But as i understand, i need someway to convert this to geojson before it can render in Google maps? if i understand correct?
As i understand to render geojson is mostly the same as to render kml when it comes to files. But i don't know how to Connect to a database.
I make a list from database:
var adresses = _unitOfWork.GeoAddressRepository.Get(q => q.GeoRouteNorpost.Code == "3007106", includeProperties: "GeoRouteNorpost").ToList();
var points = new List<LatLong>();
foreach (var address in adresses)
{
points.Add(new LatLng() { Lat = "59.948261", Lng = "10.750699" });
points.Add(new LatLng() { Lat = "59.943128", Lng = "10.755814" });
points.Add(new LatLng() { Lat = "59.941245", Lng = "10.746084" });
points.Add(new LatLng() { Lat = "59.943527", Lng = "10.742786" });
points.Add(new LatLng() { Lat = "59.946824", Lng = "10.744435" });
points.Add(new LatLng() { Lat = "59.946813", Lng = "10.744446" });
points.Add(new LatLng() { Lat = "59.947107", Lng = "10.748241" });
points.Add(new LatLng() { Lat = "59.947827", Lng = "10.749525" });
points.Add(new LatLng() { Lat = "59.948248", Lng = "10.750699" });
}
This example show a polygon on a map. But i'm not sure how to get this coordinates out of the database and how to solve it when it is serveral polygons.
As i have written, i have saved the coordinates in the db With shape2Sql. So now i have a Field for geometry. If i look at the spatial result in sql server this looks correct. But how can i display this in Google maps?
I am grateful for all help:)

gmaps4rails V2 get markers

I'm storing the data like in scope of markers variable for google maps (gmaps4rails gem)
Gmaps.store = {} #handler, markers
jQuery ->
Gmaps.store.handler = Gmaps.build 'Google'
Gmaps.store.handler.buildMap { internal: {id: 'map'} }, ->
Gmaps.store.markers = ....
How do I get the markers back? Gmaps.store.markers doesn't work.
Retrieve data in the callback to be sure they exist, adding a timer is very erratic.

Encoded path in MySQL database

I have encoded the paths of several polylines using google.maps.geometry.encoding.encodePath() and want to store them in a MySQL table.
Problem: Before storing them into the table, I drew out the polylines as shown in the top half of the image below. However, after storing them into the table, retrieveing them and drawing again, the path seems to have changed! What happened?
Additional Info: I notice that if i were to write the freshly encoded path to console.log, copy from the console log and use this copied path to draw a new polyline, the polyline gets distorted at certain areas, just like what happened after using the encoded path that was retrieved from the database!
Update
Polyline using freshly encoded path
JS Code
encoded_path = google.maps.geometry.encoding.encodePath(path);
console.log(encoded_path);
decoded_path = google.maps.geometry.encoding.decodePath(encoded_path);
var polyOptions = {
strokeColor: "#970E04" ,
strokeOpacity: 1.0 ,
strokeWeight: 2 ,
path: decoded_path ,
clickable: false,
map: map
}
polyline = new google.maps.Polyline(polyOptions);
Encoded path from console.log
axwaGtbcqLBgArBmAjCcBlBcCnBeChB_BrAmAxByBjCoCkAqBmByCu#qA[i#~BmAdAq#FEzAqAvAsA|#{#DCr#{#DIjAuA|#cAz#}#~AeB\[LZxAjDJINM|AkAxAxCfAw#g#jAeBpEOr#Ox#CTeAlMM~AYhDc#pE_AtHGj#m#Gm#dHa#hFaAbM_AfJ]jDAlA{Hhv#eAdFy#bCcBpEeBzDyArDu#E_AnFs#|Fq#fGKtKaEqCgBmB_GmFcJaM}#nBg#BbA}CpAaEvAoEnGyOvDuPDSPYAIIMMMGOMMIIKKKQIMIKIKa#gAQ_#Q[CCY_#OSQYQQOOSMSOa#]g#g#UWSUYm#Uk#]qAKe#Ia#I_#Iy#Es#C_AAw#A]Ca#G[Qy#GSKa#M]M_#Qa#M]IOGKQSGIIG}#w#{AgAiAaAWSUOWOQIMEKCICOGMCKEQC_DuA?GbByB\_#~GaIxCgDl#s#bBkBnBcBzCqCAi#pCmA^mAd#qA
Polyline using path retrieved from database
Value stored in column VARCHAR(255)
Copied using Navicat
axwaGtbcqLBgArBmAjCcBlBcCnBeChB_BrAmAxByBjCoCkAqBmByCu#qA[i#~BmAdAq#FEzAqAvAsA|#{#DCr#{#DIjAuA|#cAz#}#~AeB[LZxAjDJINM|AkAxAxCfAw#g#jAeBpEOr#Ox#CTeAlMM~AYhDc#pE_AtHGj#m#Gm#dHa#hFaAbM_AfJ]jDAlA{Hhv#eAdFy#bCcBpEeBzDyArDu#`E_AnFs#|Fq#fGKtKaEqCgBmB_GmFcJaM}#
Polyline using path retrieved from database with VARCHAR(1000)
Value stored in column VARCHAR(1000)
Copied using Navicat
axwaGtbcqLBgArBmAjCcBlBcCnBeChB_BrAmAxByBjCoCkAqBmByCu#qA[i#~BmAdAq#FEzAqAvAsA|#{#DCr#{#DIjAuA|#cAz#}#~AeB[LZxAjDJINM|AkAxAxCfAw#g#jAeBpEOr#Ox#CTeAlMM~AYhDc#pE_AtHGj#m#Gm#dHa#hFaAbM_AfJ]jDAlA{Hhv#eAdFy#bCcBpEeBzDyArDu#E_AnFs#|Fq#fGKtKaEqCgBmB_GmFcJaM}#nBg#BbA}CpAaEvAoEnGyOvDuPDSPYAIIMMMGOMMIIKKKQIMIKIKa#gAQ_#Q[CCY_#OSQYQQOOSMSOa#]g#g#UWSUYm#Uk#]qAKe#Ia#I_#Iy#Es#C_AAw#A]Ca#G[Qy#GSKa#M]M_#Qa#M]IOGKQSGIIG}#w#{AgAiAaAWSUOWOQIMEKCICOGMCKEQC_DuA?GbByB\_#~GaIxCgDl#s#bBkBnBcBzCqCAi#pCmA^mAd#qA
Polyline by decoding the encoded path written to console.log
JS Code
//encoded path copied from console.log output from the very first code in post
encoded_path = 'axwaGtbcqLBgArBmAjCcBlBcCnBeChB_BrAmAxByBjCoCkAqBmByCu#qA[i#~BmAdAq#FEzAqAvAsA|#{#DCr#{#DIjAuA|#cAz#}#~AeB\[LZxAjDJINM|AkAxAxCfAw#g#jAeBpEOr#Ox#CTeAlMM~AYhDc#pE_AtHGj#m#Gm#dHa#hFaAbM_AfJ]jDAlA{Hhv#eAdFy#bCcBpEeBzDyArDu#E_AnFs#|Fq#fGKtKaEqCgBmB_GmFcJaM}#nBg#BbA}CpAaEvAoEnGyOvDuPDSPYAIIMMMGOMMIIKKKQIMIKIKa#gAQ_#Q[CCY_#OSQYQQOOSMSOa#]g#g#UWSUYm#Uk#]qAKe#Ia#I_#Iy#Es#C_AAw#A]Ca#G[Qy#GSKa#M]M_#Qa#M]IOGKQSGIIG}#w#{AgAiAaAWSUOWOQIMEKCICOGMCKEQC_DuA?GbByB\_#~GaIxCgDl#s#bBkBnBcBzCqCAi#pCmA^mAd#qA';
decoded_path = google.maps.geometry.encoding.decodePath(encoded_path);
var polyOptions = {
strokeColor: "#970E04" ,
strokeOpacity: 1.0 ,
strokeWeight: 2 ,
path: decoded_path ,
clickable: false,
map: map
}
polyline = new google.maps.Polyline(polyOptions);
Path that did not work correctly as well
I notice that there are newlines in the middle of these encoded strings? Also, the encoded string splits the line of code into 2 lines, causing the error checking system in my editor to show an alert.
JS Code (Malformed)
encoded_path = '{traGxcspLaIkFvAwH}BgA{EzEjCgJmEwBmDvGoHpAkLQpAqGyF_CbCuH^}FlDwEo
Cyn#y#g[yL{c#wb#e#sG#kHgEaBiJ}EiHzMwLdFga#{U{KoZoZhH{e#hh#~RlBgJ{AgMrAkQrD[rCl#pNmAhJeCgDhQdGlItBpQbTb#EdQoBtMaJzSoEf#bMzLlHRj#lHrFhCnHrNvAk#qBeOpAcAlRvCfEgQt#oB_JeBmTmL}DqJl#qHbCmEzFc]xr#nT|IoKf#RlGdFtCuMpEzAbS}[qGe{#dOsEnGjZhInDrHwIjEdH_OtdAf#~WnM`F~AyN_DgEzh#nKgTvVbBrNoZvB_SvLwGfJwT~w#wG?gBzB?xFdAt#xFn#bBve#?nPoKv[kGwBsCdGoCtBwFoBwCfFcBvBoArDsC]{AxA';
Encoded Path
{traGxcspLaIkFvAwH}BgA{EzEjCgJmEwBmDvGoHpAkLQpAqGyF_CbCuH^}FlDwEo
Cyn#y#g[yL{c#wb#e#sG#kHgEaBiJ}EiHzMwLdFga#{U{KoZoZhH{e#hh#~RlBgJ{AgMrAkQrD[rCl#pNmAhJeCgDhQdGlItBpQbTb#EdQoBtMaJzSoEf#bMzLlHRj#lHrFhCnHrNvAk#qBeOpAcAlRvCfEgQt#oB_JeBmTmL}DqJl#qHbCmEzFc]xr#nT|IoKf#RlGdFtCuMpEzAbS}[qGe{#dOsEnGjZhInDrHwIjEdH_OtdAf#~WnM`F~AyN_DgEzh#nKgTvVbBrNoZvB_SvLwGfJwT~w#wG?gBzB?xFdAt#xFn#bBve#?nPoKv[kGwBsCdGoCtBwFoBwCfFcBvBoArDsC]{AxA
The slashes in the string literal returned by encodePath() are being interpreted prior to write, whether the write is to screen or to database.
What I would do is escape the slashes at the earliest possible point:
encoded_path = google.maps.geometry.encoding.encodePath(path);
encoded_path = encoded_path.replace(/\\/g,"\\\\");
This should ensure that the string written to the database (or log) is correct, and you shouldn't have to do anything special on the read.
Alternatively, you can escape the slashes right before passing the string into another medium, such as just prior to your AJAX call or, as mentioned in the comments, in the console.log() method call.