How to eliminate the button from Google Maps API using JavaScript

I am trying to implement a specific functionality on my map. When the user drags the map, I want a button named 'Search in this area' to appear. Once the user clicks on the button, it should disappear so that the search can't be performed again in the same area. However, after dragging the map again, the button should reappear.

Below is the code snippet:

  controlMarkerUI = document.createElement('div')
  controlText = document.createElement('div')

  mapReady(map) {
    this.my_map = map
    var self = this
    google.maps.event.addListener(this.my_map, 'dragend', function () {
      self.redo_search_button(self.my_map)
    });
  }

  redo_search_button(map) {    
    this.controlMarkerUI.style.cursor = 'pointer'
    this.controlMarkerUI.style.backgroundColor = '#fff';
    this.controlMarkerUI.style.marginTop = '10px'
    this.controlMarkerUI.style.border = '2px solid #fff'
    this.controlMarkerUI.style.borderRadius = '3px'
    this.controlMarkerUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)'
    this.controlMarkerUI.style.textAlign = 'center'
    this.controlMarkerUI.title = 'Click to redo search in this area'

    this.controlText.style.color = 'rgb(25,25,25)';
    this.controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
    this.controlText.style.fontSize = '16px';
    this.controlText.style.lineHeight = '38px';
    this.controlText.style.paddingLeft = '5px';
    this.controlText.style.paddingRight = '5px';
    this.controlText.innerHTML = 'Search in this area';

    this.controlMarkerUI.appendChild(this.controlText);
    map.controls[google.maps.ControlPosition.TOP_CENTER].push(this.controlMarkerUI)

    var this_ = this
    this.controlMarkerUI.addEventListener('click', function () {
      this_.redo_search() // refresh the markers
      this_.removeDummy()
    });
  }

I attempted to create a function like this:

  removeDummy() {
    this.controlMarkerUI.parentNode.removeChild(this.controlMarkerUI);
    return false;
  }

This function successfully hides the button but shifts it to the right when the map is dragged, which is not the desired behavior.

Answer №1

  1. Hide your button style by setting it to none upon creation.

this.controlMarkerUI.style.display = 'none'

  1. Add an event listener to the button to hide it when clicked.
  2. Add an event listener to the map to display it when dragging ends.

See a complete working example below:

var map;
function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(10, 10),
        zoom: 5
    };

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    // Customize the control button's CSS
    var controlUI = document.createElement('div');
    controlUI.style.backgroundColor = '#444';
    controlUI.style.borderStyle = 'solid';
    controlUI.style.borderWidth = '1px';
    controlUI.style.borderColor = 'white';
    controlUI.style.height = '28px';
    controlUI.style.marginTop = '5px';
    controlUI.style.marginLeft = '5px';
    controlUI.style.cursor = 'pointer';
    controlUI.style.textAlign = 'center';
    controlUI.style.display = 'none';

    // Customize the control text's CSS
    var controlText = document.createElement('div');
    controlText.style.fontFamily = 'Arial,sans-serif';
    controlText.style.fontSize = '10px';
    controlText.style.color = 'white';
    controlText.style.paddingLeft = '10px';
    controlText.style.paddingRight = '10px';
    controlText.style.marginTop = '8px';
    controlText.innerHTML = 'My button text';
    controlUI.appendChild(controlText);

    // Set up click event listeners to hide the button
    google.maps.event.addDomListener(controlUI, 'click', function() {
        this.style.display = 'none';
    });

    // Add the button to map controls
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(controlUI);

    // Set up an event listener to show the button when dragging ends
    google.maps.event.addListener(map, 'dragend', function() {
        controlUI.style.display = 'block'
    });
}
#map-canvas {
  height: 160px;
}
<div id="map-canvas"></div>

<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initialize">
</script>

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

Discovering the power of Angular 2 with ngrx while putting my Reducer to the

Within my Reducer file: case PumpActionTypes.EnterLocalMode: return commandOne.upsertOne( {id: action.payload.id, changes: { local: false }}, state ); When testing, I aim to verify that the local property is indeed modified to false. My curr ...

Executing angular 1 and angular 4 simultaneously within one browser tab

Is there a way to open my AngularJS 1 app running on port 3020 and an angular 4 app on port 4200 in the same tab by clicking a link? ...

What is the maximum allowable size for scripts with the type text/json?

I have been attempting to load a JSON string within a script tag with the type text/json, which will be extracted in JavaScript using the script tag Id and converted into a JavaScript Object. In certain scenarios, when dealing with very large data sizes, ...

Error: Interface declaration for _.split is missing in the Lodash.d.ts file

For my current typescript project that heavily relies on Lodash with lodash.d.ts, I've encountered an issue with the _.split function not being implemented yet. It's listed under the 'Later' section in the .ts file. I need to find a wo ...

Using res.locals with TypeScript in Next.js and Express

In my express - next.js application, I am transferring some configuration from the server to the client using res.locals. My project is written in typescript and I am utilizing "@types/next": "^8.0.6". The issue at hand: typescript is throwing an error st ...

Angular select element is not functioning properly with the `addEventListener` method

My current project involves creating a table using the primeng library. The table consists of three rows and three columns, and all the data is static. Even though I am utilizing an external library, I find myself traversing the DOM directly. <p-table ...

Ways to indicate a checkbox as selected within angular version 4

I'm a complete beginner in Angular 2 and I need to be able to check checkboxes when a button is clicked. I have multiple checkboxes generated in a loop like this: <tr *ngFor="let roleObj of roleNameList"> <td> <input ty ...

React JS displayed the string of /static/media/~ instead of rendering its markdown content

When I looked at the material UI blog template, I created my own blog app. I imported a markdown file using import post1 from './blog-posts/blog-post.1.md'; Next, I passed these properties to this component like so: <Markdown className=" ...

Unexpected results observed in enumerators within typescript

Could someone clarify the results that I am seeing from the code below? enum days { sun = 1, mon = 0, tues }; console.log(days[1]); // outputs tues // should output -- mon console.log(days[0]); // outputs mon // should output -- sun Furthermore, how ...

Encountered a bug in the findUnique function within the services of a Nest JS and Prisma project

I have a question about using Prisma with Nest. I keep encountering this error: src/modules/auth/auth.service.ts:28:63 - error TS2322: Type 'UserWhereUniqueInput' is not assignable to type 'string'. 28 const user = await this.prisma ...

Encountering the following error message: "Received error: `../node_modules/electron/index.js:1:0 Module not found: Can't resolve 'fs'` while integrating next.js with electron template."

I am utilizing the electron template with next.js, and I am trying to import ipcRenderer in my pages/index.tsx file. Below is the crucial code snippet: ... import { ipcRenderer } from 'electron'; function Home() { useEffect(() => { ip ...

What is the best way to incorporate data from a foreach method into a function call within an HTML string?

Having trouble calling a function with data from a foreach loop while generating HTML cards and buttons from an array. The issue seems to be in the renderProducts() method. /// <reference path="coin.ts" /> /// <reference path="prod ...

The Angular selector is unrecognized: double-check that it belongs to the current module if it is an Angular component

After creating a component, I attempted to utilize it in another component by specifying its selector in the display segment. <app-component1></app-component1> However, I encountered a compile error. Upon reviewing the imports in the modules, ...

Split the form into separate pages or views using Angular

We are tasked with creating a single page application using the latest Angular 6 technology for an insurance company. The form consists of 9 questions, and the client has requested that only one question be displayed on the screen at a time. Upon clicking ...

having difficulty configuring drizzle on express

When configuring the database connection with MySQL using drizzle, I encountered a puzzling situation. I am utilizing express and top-level await without async, but I'm unsure of how it all fits together. import { drizzle } from "drizzle-orm/mysq ...

What is the best way to deliver a downloaded document to a client using NodeJS Express?

I am facing an issue with downloading files from my FTP server using a button on my front-end website. The FTP server is password protected, and only I as the admin have access to the password. However, when the user clicks the download button, the file ge ...

The malfunctioning collapse feature in Bootstrap 4 sidebar within an Angular 6 application

I am trying to find a way to collapse and reopen the sidebar when clicking on a button. I have attempted to create a function to achieve this, but unfortunately it did not work as expected. Important: I need to collapse the sidebar without relying on jque ...

The checkbox confirmation button appears to be absent in the ngx mat date time picker

I encountered a styling issue with the ngx mat datetime picker in my Angular 15 project. You can find the package here. To resolve the issue, I included @import "https://fonts.googleapis.com/icon?family=Material+Icons"; in my styles.scss file, and that re ...

Tips for properly narrowing a function parameter that includes "an object key or a function"

Working on a function to retrieve a property using either a string key or a callback, I've encountered an issue with TypeScript narrowing the type parameter. Here is the function in question: function get<T, V>(value: T, fn: (value: T) => V) ...

Insufficient attributes in TypeScript component for React application

Developing with React import {Input} from '@xxx/forms'; <Input label="account Name" name="account"/> Type Definition for input import React, { Ref } from 'react'; import { InputProps as UITKInputProps } from ...