Removing a pin from google maps using a personalized delete button

I have encountered an issue while attempting to remove a marker from Google Maps using a custom delete button within the info window. Even though I have successfully added the button and necessary information, it seems that the function responsible for deleting the marker is not being called when the delete button is pressed.

Below is the code snippet showcasing the implementation:

function initMap() {

var jsonData = {$pointsArray};

var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 4,
       maxzoom: 15,
        center: {
           lat: 38,
           lng: -77
         }
     });

 function addInfoWindow(marker, message) {

         var infoWindow = new google.maps.InfoWindow({
             content: message
         });

         google.maps.event.addListener(marker, 'click', function () {
             infoWindow.open(map, marker);
         });
     }

 var bounds = new google.maps.LatLngBounds();
 var uniqueId = 1;
 var markers = [];

 for (var i = 0, len = jsonData.length; i < len; ++i) {

    var point = jsonData[i];
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(point.Lat, point.Lon),
        map: map,
        title: point.Title
    });

 bounds.extend(marker.position);
 marker.id = uniqueId;
 uniqueId++;

    var contentString = '<div id="content">'+
                     '<h4 id="pointId" > ' + point.Title + '</h4>'+
                     '<h6 >City: ' + point.City + '</h6>'+
                     '<h6 >Latitude: ' + point.Lat+ '</h6>'+
                     '<h6 >Longitude: ' + point.Lon + '</h6>'+
                     '<h6 >Address: ' + point.Address + '</h6>'+
                     '<p data-placement="top" data-toggle="tooltip" title="Delete"><a href="" onclick= "DeleteMarker( "+ marker.id +"  );"  class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal"><span class="glyphicon glyphicon-trash"></span></a></p>'

                    '</div>';
    addInfoWindow(marker, contentString);
    markers.push(marker);
 }

 function DeleteMarker(id) {

    for (var i = 0; i < markers.length; i++) {
        if (markers[i].id == id) {
            markers[i].setMap(null);
            markers.splice(i, 1);
            return;
        }
    }
};

  map.fitBounds(bounds);
 }

It appears that there might be an issue with the onclick attribute in the delete button. Any assistance or guidance on resolving this problem would be greatly appreciated!

Answer №1

In my opinion, in order to pass marker.id as a parameter, it is essential to use single quotes ('), rather than double quotes ("), because you have already used double quotes for the attribute value and using them again would disrupt the onclick value string.

Answer №2

When you view the final HTML output, your function should be structured like this:

<p><a onclick="DeleteMarker('some id');"</a></p>

To accomplish this, make sure to enclose your id parameter in additional single quotes:

onclick="deleteMarker('+"'"+ yourId +"'"+')

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

What is the best way to incorporate a JSON file into a JavaScript class?

I attempted to load a JSON file within a JavaScript class, but encountered an issue where the loaded data was only accessible inside a specific function. class CreatePage { constructor() { var request = new XMLHttpRequest(); request. ...

Searching for a specific field within an array in a nested subdocument in MongoDB: What you need to know

I am having trouble retrieving lookup data for an embedded array within a document. Below is a snippet of the data: { "_id": "58a4fa0e24180825b05e14e9", "fullname": "Test User", "username": "testuser" "teamInfo": { "chal ...

Application with menu design, similar to the layout of google.com on mobile devices

Have you seen the Android smartphone with Chrome from GOOGLE.COM? Did you notice the pop-up MENU that looks similar to an application? This menu has a "SPRING" effect, and I'm curious how Google achieved this result. I tried using the property "-web ...

Finding elements in an array based on a specific string contained within a property

I am currently working on filtering JSON data to specifically search for job roles that begin with a particular string. The structure of the JSON is as follows : "periods": [ { "periodName": "Week1", "teamName": "Tango", ...

When using momentJs to add days, it will return a moment object rather than a

How can I add 7 days to a date using momentJs in my Angular project? let startDate = "2018-08-16T02:00:00.242Z"; let newDate = moment(startDate).add(7, 'days'); I was expecting to receive the date after adding 7 days, but instead I get a momen ...

Securely transmit data using a JQuery modal dialog form with HTTPS encryption

I currently have a functional modal login dialog. The only issue I'm facing is that when the original page is loaded through http, I still need to securely pass credentials to the server via https. Ideally, I would like to achieve this with minimal mo ...

The server is constantly sending data through Server Sent Events

I am currently a student working on a project involving a social trading platform. I am looking to incorporate a notification system and believe that SSE would be a great fit for this purpose. However, I am facing an issue where my SSE code is sending data ...

Tips for handling HTTP responses prior to initializing a data-table in AngularJS

Here is a snippet of code showcasing a process involving multiple http requests and the use of promises: The first step involves calling a service to initiate an http request. Upon receiving the response, a map is created based on the data, which will be ...

Issues with utilizing jQuery AJAX for form submissions

I am currently customizing a webpage to fit the specific requirements of a client using a template. The page contains two contact forms which are being validated and sent to a PHP file via AJAX. One of the forms is standard, while the other one has been mo ...

Can a mutable static class variable be created in JavaScript?

I have an idea similar to this concept: class Example { static var X; static setX(value) { this.X = value; } static getX() { return this.X; } } This allows the variable to be stored within the class and easily modified ...

TinyMCE - Optimal Approach for Saving Changes: keyup vs onChange vs blur

In the context of my Filemaker file, I am utilizing the TinyMCE editor. My goal is to automatically save any changes made by the user, whether it's typing, applying formatting, inserting an image, or making any other modifications. I have a function ...

Exploring the Depths of React by Cycling Through Arrays in Tabular Format

One issue I'm facing is that I have an array named paymentMethods which I'd like to iterate through in tabs. However, I seem to be struggling with the iteration part. To take a closer look at my code, please visit my codesandbox HERE <div& ...

Retrieve information using Observables just once in Angular 2

One of my Angular 2 components relies on a service that fetches customer data from a Web API and returns an Observable: getCustomers() { return this.http .get(this.baseURI + this.url) .map((r: Response) => { let a = r.jso ...

What causes the DOM's appendChild() to trigger on('load', ...) while jQuery's append() does not fire?

I have two snippets of code that I am working with: $(document).ready(function() { document.head.appendChild( $('<script />').attr('src', 'source.js').on('load', function() { ... ...

Transforming Django models into JSON format to be utilized as a JavaScript object

Looking to retrieve model data as an object in Javascript, I've been using the following approach in my Django view: var data = {{ data|safe }}; Here is how my view is set up: context = { 'data': { 'model1': serializ ...

Send an AJAX request to the server without waiting for a response using a JavaScript variable

My click counter is not sending variables to the server. I have tried finding examples on how to do this, but no matter what I attempt, the data is not being sent to the server. It seems like using AJAX would be the best option, but I must be doing someth ...

Website experiencing issues with moderating Facebook comments

I recently added a Facebook comments box to my website in the footer. Although it is visible, I am unable to moderate it. Furthermore, the comments are not showing up in the comments queue panel at https://developers.facebook.com/tools/comments. I am us ...

Sending various types of data to an MVC C# controller using AJAX

Currently, I am utilizing AJAX to retrieve information from a Razor View and forward it to the controller. Although everything is functioning as expected, I now face the challenge of passing an array along with a string as the data: // View - JavaScript v ...

Learn how to change the input source in Ratchet's chat app to come from a text box on the webpage instead of the console

I followed the guidelines on to create a chat app. However, I now want to input data from a text box instead of using conn.send() in the console. How can I achieve this using php? I was successful in redirecting the sent message to an html element like ...

Prevent text from wrapping when using jQuery to animate font size

I have a unique way of showcasing content in a preview format by utilizing em units for scaling and adjusting the root font size to increase or decrease. When users click on the preview, the full content is revealed with an animation that scales the font s ...