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

Exploring the world of form interactions in Angular: A guide to creating dynamic element communication

I have created a form using Angular, and I want to display a specific value in my input field when an element is selected from the dropdown. Additionally, since the values in the dropdown are fetched from a server, I want to show a corresponding label for ...

Exploring the Functionality of Cookies in Nuxt 3 API Endpoints and Middlewares

Can cookies be utilized on the server side in Nuxt 3? For instance, I need to set a cookie in an API and then access its data in middleware: // ~/server/api/testApi.ts export default defineEventHandler(event => { /* setCookie('myCookie', ...

Use JavaScript to upload a JSON file containing arrays into separate tabs

Looking for help with incorporating JSON data into an HTML template that features tabs and a gallery? Take a look at my setup below: <div class="tab"> <button class="tabLinks" onclick="openDiv(event, 'overview'); appendData()" id= ...

How to properly format credit card input using JavaScript or jQuery

I need to implement a feature where users input their credit card information, and once they complete the form, I want to display the credit card number in this format: xxxxxxxxxxxx1111 or xxxx-xxxx-xxxx-1111, without altering the actual input value. Is ...

The AJAX request is functioning properly, however, when I attempt to click the icon within the button, a 500 internal server error is triggered

Encountering a 500 internal server error specifically when attempting to click the thumbs-up icon within the like button: <button class="submit-btn like" id='{{ $image->id }}'> <i class="far fa-thumbs-up"></i> Like </ ...

Incorporating user input into a div element

So, I'm in the process of building my own Task Tracker using JavaScript to enhance my skills, but I've hit a roadblock. I successfully implemented adding a new div with user-inputted tasks, however, there's no styling involved. <div cla ...

Angular material is experiencing an issue where content is being cut off or

I am currently working on a project using AngularJS for a web application. I have encountered an issue where some of the content in the md-content element is being clipped. For instance, the body tag has the style: overflow: hidden, and the child md-conte ...

Update the content of an HTML element without having direct access to the HTML code

I am currently in the process of creating a website using a website builder, and I am interested in customizing the default message that is displayed when a required field in the website form is left empty. The form in question is an integral part of the w ...

The comparison between exposing and creating objects in a Nodejs router file

Recently, I began using expressjs 4.0.0 and was impressed by the express.Router() object. However, a dilemma arose when I moved all my routes to another file - how do I expose an object to the routes file? In my server.js file: ... var passport = ...

The functioning of JavaScript's ajax capabilities

Need some help with a coding issue I'm facing. Can anyone provide suggestions for improving my code? I've come across a situation where the table is not updating when using a certain piece of code. However, upon further inspection, I found that ...

Tips on preventing flickering when using javascript for drag and drop functionality

I have implemented the following JavaScript code (using jQuery) to manage drag and drop functionality in a script I am developing: jsc.ui.dragging = false; jsc.ui.drag_element = {}; $(".drag-target").mousedown(function() { jsc.ui.drag_element = $(thi ...

What is the best way to transfer the search query to a table filter when working with multiple JavaScript files?

I am struggling with passing the search query from my search file to my table file. The data for my datagrid table is retrieved from a database using an API call, and the table code is in one file while the search functionality code is in another file. I h ...

The autoIncrement feature is causing a syntax error at or near "SERIAL"

Encountering a build error : Unable to start server due to the following SequelizeDatabaseError: syntax error at or near "SERIAL" This issue arises only when using the autoIncrement=true parameter for the primary key. 'use strict'; export ...

Change the color of this element and input field background

Having trouble with setting the background color of an input field to red in this code: $(document).ready(function(){ $(".abc").focus(function(){ $(this).attr('background', 'red'); $("label").text('Insert tex ...

Trouble Navigating the DOM

Can you assist me in choosing the correct option c? Below is the provided HTML code: <div id="a"> <div id="b"></div> <div id="app7019261521_the_coin_9996544" style="left: 176px; top: 448px;"> <a href="d.com" oncl ...

Guide on implementing a personalized 'editComponent' feature in material-table

I'm currently integrating 'material-table' into my project. In the 'icon' column, I have icon names that I want to be able to change by selecting them from an external dialog. However, I am encountering issues when trying to update ...

What is the best way to eliminate a duplicate item from the shopping cart without actually deleting it?

I developed an e-commerce platform with a cart feature using the context API. However, I encountered an issue where removing one item from the cart also deletes another item if there are two of the same items in the cart. How can this be prevented? Below ...

Vue paired with Rainyday.js

I attempted to incorporate Vue with rainyday.js by following different resources, but unfortunately could not find any relevant information. Can anyone provide guidance on how to successfully implement rainyday.js with Vue? <body onload="run();"> ...

The MaterialUI FormControl API TextField is experiencing an issue where the onClick event does not trigger on the initial click

I am currently working on a React application where I have integrated a MaterialUI Form Control API TextField. However, I am facing an issue with the Select tag as the onClick method is only firing after the first click. There are no hidden CSS properties ...

The object in question does not have the capability to support the "live" property or method

I've encountered an issue in IE related to a script error with the live method. The problem arises when testing on the website URL @ Despite trying multiple solutions and various fixes, I haven't been able to resolve the issue yet. Any assistanc ...