Ziarno
Ziarno

Reputation: 7562

Can't save polygon in google maps

I have a google maps polygon object:

var poly = new google.maps.Polygon({
  paths: [
    new google.maps.LatLng(25.774252, -80.190262),
    new google.maps.LatLng(18.466465, -66.118292),
    new google.maps.LatLng(32.321384, -64.75737)
  ]
});

I'm trying to send it to MySQL db via jquery's AJAX:

$.post("savePolygon.php", {polygon: poly});

I get this error in console:

TypeError: Cannot call method 'lat' of undefined

I've seen some other posts about saving polygons, and they all say to extract the latLng's from the poly's and save them in a db. When I do this though:

var latLngs = poly.getPath().getArray();
$.post("savePolygon.php", {polygon: latLngs});

I get the same error. It seems there is a function in array's prototype called 'lat'. I'd like to know how exactly can I extract those values and send them via AJAX, and also why do I get this error?

Upvotes: 1

Views: 1756

Answers (1)

Dr.Molle
Dr.Molle

Reputation: 117314

Use google.maps.geometry.encoding.encodePath() to encode the path. This method returns a string, perfect for storing into a DB. For reuse decode the string by using google.maps.geometry.encoding.decodePath()

Please note: the geometry-library isn't loaded by default, you must load it by appending &libraries=geometry to the src of the maps-API-script.

To explain why you can't store the path directly(e.g. as JSON):
when you store the path(array), which contains the LatLng's, you will lose the prototype of the LatLng's, which is essential because it defines the methods for retrieving the properties(lat() and lng() )

Upvotes: 5

Related Questions