Managing location markers with Google Maps API V3: Saving and removing locations

I encountered an issue while using GMAP V3. After realizing the need to save map changes in a database, I struggled to find a way to accomplish this task. Before attempting any workarounds, I thought it would be best to gather some ideas first. The community at stackoverflow has always provided me with great insights and solutions for my problems, so I am turning to them once again.

Here's the situation:

I have a script that calculates the elevation of a region, and I have manually added some data to my code as shown below:

  var examples = [{
    latlngs: [
      [-24.116537, -49.358257],
      [-24.123348, -49.344267],
      [-24.122409, -49.329212],
      [-24.116478, -49.306664],
      [-24.101001, -49.313376],
      [-24.095218, -49.333645]
    ],
    mapType: google.maps.MapTypeId.SATELLITE,
    travelMode: 'direct'
    }, {
    latlngs: [
      [-23.991412, -48.894621],
      [-23.969345, -48.884353],
  [-23.973734, -48.855789],
  [-23.996274, -48.860673],
  [-24.00085, -48.886786]
    ]
    mapType: google.maps.MapTypeId.SATELLITE,
    travelMode: 'direct'
   }];

Now let's initialize everything:

  function initialize() {
    var myLatlng = new google.maps.LatLng(15, 0);
    var myOptions = {
      zoom: 1,
      center: myLatlng,
      mapTypeControl: true,
      mapTypeId: google.maps.MapTypeId.TERRAIN
    }

Next, we have a function to add markers on the map:

// Add a marker and trigger recalculation of the path and elevation
  function addMarker(latlng, doQuery) {
    if (markers.length < 100) {

      var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        draggable: true
      })

      google.maps.event.addListener(marker, 'dragend', function(e) {
        updateElevation();
      });

      markers.push(marker);

      if (doQuery) {
        updateElevation();
      }

      if (markers.length == 100) {
        document.getElementById('address').disabled = true;
      }
    } else {
      alert("Apenas 100 pontos podem ser adicionados.");
    }
  }

So far, everything is functioning correctly. However, I now need to enhance the map by adding a new marker and a save button to allow saving changes to the database. Is there a built-in function within the GMAP API that can facilitate this process?

Another issue I faced is the ability to delete a single marker. Currently, I can only delete all markers at once, but I require the functionality to delete individual markers.

I believe the function addMarker with var marker could potentially be used to store values in a database, but how exactly should I go about implementing this?

Answer №1

It would be beneficial for you to analyze your code and look for ways to separate these features. One approach could be creating a generic wrapper for the Google Maps API. I have developed one that you can check out here:

This wrapper demonstrates how you can manipulate individual markers.

Another area to consider separating is your database interactions, which can be handled through AJAX. I suggest using a library like jQuery to handle cross-browser compatibility. You can organize your database calls within a JavaScript object or at least place them in the event handler for the 'save' button. Here's an example of an AJAX call using jQuery:

var data = {};
data.lat = 89.0;
data.lng = -10.0;
data.name = 'marker name';
$.ajax({
    url: 'api/1.0/markers/save.php',
    type: 'post',
    data: data,
    error: function(){
        alert('Error on ajax.');
    },
    success: function(data){
       alert('success...do other stuff here');
    }
});

I hope this information proves useful.

Sincerely,

Bob

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

Anticipating the resolution of one promise before tackling the next in Angular.js

Is it possible in Angular.js to ensure that a given promise is resolved before another dependent promise? Consider the following code snippet: User.getAllUsers().then(function(users) { $scope.users = users; for (var i = 0; i < users.length; i+ ...

Trying to configure and use two joysticks at the same time using touch events

I have been grappling with this problem for the past two days. My current project involves using an HTML5/JS game engine called ImpactJS, and I came across a helpful plugin designed to create joystick touch zones for mobile devices. The basic concept is th ...

Angular - Dividing Functionality into Multiple Modules

I am currently working with two separate modules that have completely different designs. To integrate these modules, I decided to create a new module called "accounts". However, when I include the line import { AppComponent as Account_AppComponent} from &a ...

Error message: "Window object not defined during NextJS build process."

Why am I encountering a 'window not defined' error? I haven't referenced window or document in my code, and it runs without issues during development but throws an error during the build process. ReferenceError: window is not defined at ...

Discover how to achieve the detail page view in Vue Js by clicking on an input field

I'm a beginner with Vuejs and I'm trying to display the detail page view when I click on an input field. <div class="form-group row"> <label for="name" class="col-sm-2 col-form-label">Name</label> ...

Vue 3 throws an error stating: "An uncaught DOMException occurred because the string contains an invalid character."

Exploring the capabilities of vue.js on a basic website. The setup consists of a single index.html file and all JavaScript is housed in an index.js file. The website is a work in progress, but there are no blockers preventing the JavaScript functionality ...

HTML Option Absent from Blend VS2013

After recently installing VS2013 Pro in Office, I was excited to use Blend and its HTML Option. However, I am struggling to find a way to start an application with html as shown in videos. My goal was to utilize Blend for creating prototypes using html. D ...

The website flickers in and out as it loads

My site keeps flashing whenever it loads. Despite trying the solutions recommended in this stackoverflow post, I have had no success. Every page on my website loads a nav.html file using this code: $.get("nav.html", function(data){     $("#nav-placeho ...

Develop a design utilizing a foundational database entity

I'm new to AngularJS and I am seeking guidance on how to properly separate the model from the controller. In my previous experience, I have always integrated models within the controllers. For example: angular.module("app").controller("customerContr ...

Exploring the realms of development and production with Next JS and Vercel

I've recently developed a movie database application using Next JS to explore its functionality. This app allows users to create, read, update, and delete data in Firebase by utilizing the API endpoints provided by NextJS. While the app works smoothl ...

There seems to be a lack of response from the Foursquare API in Node.js

Seeking guidance on retrieving a photo from a Foursquare venue using Node.js platform. Despite having the correct id and secret, the code is returning an unexpected result. My goal is to obtain the prefix and suffix of the image to properly display it as o ...

Rendering a Component Inside Another Component

I am facing a situation where I have a component named TicketView being used within another component called Table. The initialization of TicketView in the table looks like this: <TableRow key={index}> ... <TableRowColumn style={{width: & ...

Having trouble transferring information from a form to a page because of the error message " is not defined"?

I'm facing an issue while building a node app. I have set up my routes correctly and installed all the necessary dependencies. However, when I try to load the ("/) "homepage," I receive an error message stating that "newPost" is not defined. Surprisin ...

Using jQuery checkboxes with ajax for data submission and storage in PHP without the need for insertion

Seeking guidance on how to properly serialize elements value instead of pushing it, as I am encountering an issue where each value is being inserted into the database 9 times. Any assistance in figuring out this problem would be highly appreciated. The HT ...

Using a string to access a property within a ReactJS object

I am looking to simplify my React Component by referencing a JS object property using a string. This will allow me to remove repetitive conditional statements from my current render function: render() { const { USD, GBP, EUR } = this.props.bpi; ...

Passing a reference to a react functional component (react.FC) results in a type error: The property ref is not recognized on the type 'IntrinsicAttributes & Props & { children: ReactNode}'

Currently, I am working on mastering the utilization of forward refs. In a functional component (FC), I am trying to initialize all my refs and then pass them down to its child components so that I can access the canvas instances of some chartjs charts. Ho ...

Error Received While Attempting to Log in using Ajax

Having an issue with logging in using ajax and php. I am able to log in successfully, but when trying to display an alert message and refresh the page upon login, it gives me an error without refreshing. However, upon manually refreshing the page, I can se ...

What is the technique for wrapping a component with a rectangle box in ReactJs?

Do you like the design in this example image? I attempted to create a similar layout using Material UI Box, but unfortunately, it only displays the text without rendering the box itself. Take a look at the code I used: import * as React from 'react& ...

Issue with Vue method not providing expected output

As I dive into the world of Vue, I find myself facing a peculiar issue with a method that should return a string to be displayed within a <span>. While I can successfully retrieve the correct value through console.log, it seems to evade passing into ...

Is there a way to ensure my Vue variable is declared once the page has fully loaded?

I have implemented a v-for loop in my code: <div v-for="(user, index) in users" :key="index" :presence="user.presence" class="person"> <span class="cardName h4">{{ user.name }}</span> ...