简体   繁体   中英

Saving google map polygon as rails record

As rails 3.2.18 postGIS enabled application needs to capture polygon data from google maps API.

The js is as follows:

  var poly, map;
  var markers = [];
  var path = new google.maps.MVCArray;

  function initialize() {
    var roma = new google.maps.LatLng(41.877, 12.480);

    map = new google.maps.Map(document.getElementById("map"), {
      zoom: 7,
      center: roma,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });


    poly = new google.maps.Polygon({
      strokeWeight: 3,
      fillColor: '#5555FF'
    });
    poly.setMap(map);
    poly.setPaths(new google.maps.MVCArray([path]));

    google.maps.event.addListener(map, 'click', addPoint);
  }

  function addPoint(event) {
    path.insertAt(path.length, event.latLng);

    var marker = new google.maps.Marker({
      position: event.latLng,
      map: map,
      draggable: true
    });
    markers.push(marker);
    marker.setTitle("#" + path.length);

    google.maps.event.addListener(marker, 'click', function() {
      marker.setMap(null);
      for (var i = 0, I = markers.length; i < I && markers[i] != marker; ++i);
      markers.splice(i, 1);
      path.removeAt(i);
      }
    );

    google.maps.event.addListener(marker, 'dragend', function() {
      for (var i = 0, I = markers.length; i < I && markers[i] != marker; ++i);
      path.setAt(i, marker.getPosition());
      }
    );
  }

While the map generates the polygon, I would like to, in a first instance view the LatLng points (to track what is being generated), but ultimately save the points.

A first issue is LatLng (Google) vs Lon/Lat (PostGIS). While there is always the possibility of flipping the data , I'd just assume avoid it. THis would imply some parsing of the data.

So how can the polygon points get captured to the database, individually or as a LonLat-formatted polygon? [Bear in mind I'm really not proficient in js...]

I'd probably want to make an AJAX request to a ruby script that would then save the details to the DB. You can access the individual latitude and longitude values from your event like so:

event.latLng.lat()
event.latLng.lng()

Or indeed use the lat() and lng() functions on anything that returns a LatLng object. See the docs: https://developers.google.com/maps/documentation/javascript/reference#LatLng

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM