Update and store new polygon coordinates within Google Maps

Within my rails application, I have successfully integrated a Google Maps feature utilizing the polygon drawing tool. The process of adding coordinates and saving them to the database has been executed without any issues.

The current challenge I am facing involves enabling users to edit and save modifications to the polygon shape. How can I implement this functionality effectively? One approach I am considering is to utilize a conditional statement to check if there are any saved coordinates in the database, and then load them using a listener.

HTML

<div style='width: 100%;'>
<%= hidden_field_tag(:map_coords, value = nil, html_options = {id: 'propertyCoordinates'}) %>

Javascript

function initMap() {
  var map = new google.maps.Map(document.getElementById("map"), {
  center: { lat: -40.6892, lng: 74.0445 },
  zoom: 8,
  mapTypeId: google.maps.MapTypeId.HYBRID,
});
        
var polyOptions = {
  strokeWeight: 0,
  fillOpacity: 0.45,
  strokeColor: "#FF0000",
  strokeOpacity: 0.8,
  strokeWeight: 2,
  fillColor: "#FF0000",
  fillOpacity: 0.35
};
// loads databased saved coordinates
var propertyCoords = [<%= @property.coordinates %>];
var points = [];
for (var i = 0; i < propertyCoords.length; i++) {
  points.push({
   lat: propertyCoords[i][0],
   lng: propertyCoords[i][1]
  });
}
                    
var drawingManager = new google.maps.drawing.DrawingManager({
 drawingMode: google.maps.drawing.OverlayType.POLYGON,
 drawingControlOptions: {
  position: google.maps.ControlPosition.TOP_CENTER,
  drawingModes: ["polygon"]
},
 polylineOptions: {
  editable: true,
  draggable: true
 },
 rectangleOptions: polyOptions,
 circleOptions: polyOptions,
 polygonOptions: polyOptions,
 map: map
});
            
if (typeof points !== 'undefined') {
 // My guess is to use a conditional statement to check if the map has any coordinates saved?
 } else {
 google.maps.event.addListener(drawingManager, 'overlaycomplete', function (e) {
  if (e.type !== google.maps.drawing.OverlayType.MARKER) {
  // Switch back to non-drawing mode after drawing a shape.
  drawingManager.setDrawingMode(null);
  // Add an event listener that selects the newly-drawn shape when the user
  // mouses down on it.
  var newShape = e.overlay;
  newShape.type = e.type;
  google.maps.event.addListener(newShape, 'click', function (e) {
   if (e.vertex !== undefined) {
    if (newShape.type === google.maps.drawing.OverlayType.POLYGON) {
     var path = newShape.getPaths().getAt(e.path);
      path.removeAt(e.vertex);
      if (path.length < 3) {
       newShape.setMap(null);
      }
     }
    }
  setSelection(newShape);
  });
 }
  var coords = e.overlay.getPath().getArray();
  document.getElementById("propertyCoordinates").value = coords;
  });
 }
} // END function initMap()

Answer №1

If you're seeking the functionality to edit polygons, then my demo on StackBlitz might be helpful for you:

  1. To start, draw a polygon using saved user coordinates and adjust the map bounds accordingly. You may need to use a getBounds polyfill for this step.

  2. Next, make the polygon editable in order to track any changes to its points. Take a look at the enableCoordinatesChangedEvent function.

  3. Monitor the changes and extract the updated polygon points by using the extractPolygonPoints function.

Once you have done that, proceed with implementing your business logic.

Just a heads up: Remember to add your own API key at the end of the stackblitz code in the index.html. Search for YOUR_KEY.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display information from Node.js on an HTML page

I am working on a nodejs project where I need to login on one page and display the result on another page using expressjs. Below is my code for login.ejs: <!DOCTYPE html> <html lang="en" dir="ltr"> <body> <form method="PO ...

Utilize ng-repeat to display a series of images, with the first image being placed within a unique div

My challenge lies in displaying product images using ng-repeat, where one image is located in a separate div. Let me share my code and explain what is happening. The API response provides product details and images [{"id_product":"1000","name":"Nikolaus ...

Updating an array with complex values in React using the useState hook in

I am working with a long array where I need to update the quantity under the misc array for each person. Each person in the array has a list of miscellaneous items, and each of those items can have their own array with quantities that need to be updated. T ...

"Encountered an error stating 'undefined method `each` for nil:NilClass' while working with an API

I've encountered a common error that I can't seem to troubleshoot. My goal is to access the ProPublica API for congress, but despite having a straightforward model, view, and controller setup, I keep running into issues. Interestingly, this same ...

Start the Angular $scope when the page first loads

When initializing a user session with specific data, I face the challenge of making sure that the session data is populated before it is required by certain directives in my application. Currently, I check if the local session data is empty on loading the ...

JavaScript - Fetch POST request is being terminated - Windows Error 10053

Seeking help for my JavaScript project course. The function is aborting during the fetch process. Chrome is the browser being used to test the project. It was intermittently "sending" before, but now it's not working at all. Had to run the app in Chro ...

Exploring the world of web development with a mix of

var articles = [ {% for article in article_list %} {% if not forloop.first %},{% endif %} { title: "{{ article.title }}", slug: "{{ article.slug }}", content: "{{ article.content }}", auth ...

Issue with AngularJS causing HTML input field to limit the display to only three digits

Whenever I input a number with 4 digits or more (excluding decimals) into the designated box, it mysteriously disappears once I click away (blur). Could it be due to the currency filter causing this issue? Even though the model retains the value when logg ...

Why is the Jquery console not displaying any values?

Hey everyone, I need some help with a small issue in my project. For some reason, the console.log() function in my project is not returning any values. <script> $('#search-box<?=$x;?>').blur(function() { var val = $("#search ...

Guide for accessing Javascript documentation via console?

There are many times when I am coding in Python, that I find myself wanting to quickly access the documentation for a function. In the iPython console, I can easily do this by entering dir?? which retrieves the documentation for the dir function. Is ther ...

Encase an asynchronous function inside a promise

I am currently developing a straightforward web application that manages requests and interacts with a SQL database using Express and Sequelize. My issue arises when I attempt to call an async function on an object, as the this part of the object becomes u ...

Flashing tilemap during the update process

I'm attempting to create a game map on a canvas using a JSON file produced by tiled map editor. I believe I am close to accomplishing this, but I encounter one issue. When I include the call to load the map in my update function, the map flickers on ...

The server tag is displaying an error due to incorrect formatting in the hyperlink data-binding section

I'm currently facing an issue with the formatting of my hyperlink. The text part of the hyperlink is working fine, which leads me to believe that the problem lies within the JavaScript. However, I am unable to pinpoint the exact issue. <asp:Templa ...

Playing with Data in AG-Grid using Javascript

I am working on implementing data display using AG Grid with an AJAX call, but I am facing an issue where no data is being shown in the grid. Even though my AJAX call seems to be functioning correctly and returning the desired object List, the grid itsel ...

AngularJS Reverse Geocoding Explained

I've been working on implementing reverse geocoding functionality in my Angular project, but so far I've only been able to extract the latitude and longitude coordinates from a location. Unfortunately, every time I try to use the reverse geocodin ...

Sending information from a parent component to a nested child component in Vue.js

Currently, I am facing a challenge in passing data from a parent component all the way down to a child of the child component. I have tried using props to achieve this as discussed in this helpful thread Vue JS Pass Data From Parent To Child Of Child Of Ch ...

Executing javascript code within the success function of the $ajax method in jQuery: A step-by-step guide

The code snippet below includes a comment before the actual code that is not running as expected. $(document).on('click', '#disable_url', function (e) { e.preventDefault(); var items = new Array(); $("input:checked:no ...

Exploring Illumination with Three.js

I'm interested in exploring the light properties further. I am curious about the variables used in the DirectionalLight.js and SpotLight.js source codes. Could you explain the difference between castShadow and onlyShadow? Is there a way to manage th ...

How to link an external CSS file to a Vue.js project

I created a new project using @vue/cli and now I want to add an external CSS file to my App.vue Here's what I attempted: <template> <div id="app"> <div id="nav"> <router-link to="/">Home</router-link> | ...

Getting the error message "t is not a function. (In 't(i,c)', 't' is an instance of Object)" while attempting to switch from using createStore to configureStore with React Redux Toolkit

I am attempting to switch from react-redux to its alternative react-redux toolkit but I kept encountering this issue t is not a function. (In 't(i,c)', 't' is an instance of Object) and I am unsure of its meaning. Here is the c ...