Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

334
Views
Folleto agregar nuevo marcador eliminar el anterior en la función de clase

descripción:

Usando el folleto e hice una class llamada Map para usar todas las funciones fácilmente cuando lo necesite. Todo listo, pero hay un problema simple que no puedo manejar. map on init crea un marcador en el centro, pero quiero permitir que el usuario cree un nuevo marcador al hacer clic pero elimine el anterior, si hace clic en el mapa, cree muchos marcadores, pero solo quiero un marcador.

JSFiddle

Todo lo que necesito es este código:

 if (marker) this.map.removeLayer(marker);

Pero, por supuesto, me da tal error:

ReferenceError: el marcador no está definido"

Problema:

Debido a que el marcador anterior se creó en el marker() pero el marcador nuevo se creó en la función newMarker() , así que no tengo idea de cómo puedo eliminar el let marker antiguo, hice esto antes cuando mi código no era class . cómo acceder a la variable de marker en la función de marker() .

Objetivo: (en resumen)

Solo quiero un marcador después de hacer clic en el mapa, ¡ya se han creado muchos marcadores en el mapa!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Puede inicializar un grupo de layerGrooup vacío y almacenar el marcador allí cada vez que agregue uno nuevo, puede borrar las capas del grupo de marcadores.

Además, no debe instanciar su mapa dos veces, por lo que solo tiene una referencia de mapa.

 class Map { constructor(map, lat_long) { this.map = map; this.lat_long = lat_long; this.markerLayer = L.layerGroup().addTo(this.map) }, ... newMarker(latLng) { this.markerLayer.clearLayers(); L.marker(latLng, { draggable: true }).addTo(this.markerLayer); } } 

 class Map { constructor(map, lat_long) { this.map = map; this.lat_long = lat_long; this.markerLayer = L.layerGroup().addTo(this.map) } get init() { return this.display(); } display() { this.map.setView(this.lat_long, 14); this.tile(); this.marker(); } tile() { L.tileLayer('https://tiles.stadiamaps.com/tiles/alidade_smooth/{z}/{x}/{y}{r}.png', { maxZoom: 20, }).addTo(this.map); } marker() { let marker = L.marker(this.lat_long, { draggable: true }).addTo(this.markerLayer); } newMarker(latLng) { this.markerLayer.clearLayers(); L.marker(latLng, { draggable: true }).addTo(this.markerLayer); } } let lat_long = [40.741895, -73.989308]; let leaflet = new L.map('map'); const map = new Map(leaflet, lat_long); map.init; leaflet.on('click', function(e) { map.newMarker([e.latlng.lat, e.latlng.lng]); })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.8.0/dist/leaflet.css" integrity="sha512-hoalWLoI8r4UszCkZ5kL8vayOGVae1oxXe/2A4AO6J9+580uKHDO3JdHb7NzwwzK5xr/Fs0W40kiNHxM9vyTtQ==" crossorigin="" /> <script src="https://unpkg.com/leaflet@1.8.0/dist/leaflet.js" integrity="sha512-BB3hKbKWOc9Ez/TAwyWxNXeoV9c1v6FIeYiBieIWkpLjauysF18NzgR1MBNBXf8/KABdlkX68nAhlwcDFLGPCQ==" crossorigin=""></script> <div id="map" style="height:400px"></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!