首页 > 解决方案 > How to remove existing markers and infobubbles from HERE maps

问题描述

I'm using the HERE maps API for my maps. I'm able to add a marker and infobubble whenever I click on a map. However, I want only the latest marker and infobuble on the map, and removed all the other ones. Below is my code which has all the markers and infobubble after I click on the map multiple times.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.0/mapsjs-ui.css?dp-version=1533195059" />
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-core.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-service.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-ui.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-mapevents.js"></script>

</head>
<body>
 <div id="map" style="height:550px;width:720px;"></div>

<script>
    //Step 1: initialize communication with the platform
    var platform = new H.service.Platform({
  app_id: 'devportal-demo-20180625',
  app_code: '9v2BkviRwi9Ot26kp2IysQ',
      useHTTPS: true
    });
    var pixelRatio = window.devicePixelRatio || 1;
    var defaultLayers = platform.createDefaultLayers({
      tileSize: pixelRatio === 1 ? 256 : 512,
      ppi: pixelRatio === 1 ? undefined : 320
    });

    //Step 2: initialize a map  - not specificing a location will give a whole world view.
    var map = new H.Map(document.getElementById('map'),
      defaultLayers.normal.map, {pixelRatio: pixelRatio});

    //Step 3: make the map interactive
    // MapEvents enables the event system
    // Behavior implements default interactions for pan/zoom (also on mobile touch environments)
    var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));

    // Create the default UI components
    var ui = H.ui.UI.createDefault(map, defaultLayers); 




function setUpClickListener(map) {
  map.addEventListener('tap', function (evt) {
    var coord = map.screenToGeo(evt.currentPointer.viewportX,
            evt.currentPointer.viewportY);
     addMarker(coord);
  });
}

function addMarker(coordinates){
    var marker = new H.map.Marker({lat:coordinates.lat, lng: coordinates.lng});
    map.addObject(marker);

    var bubble =  new H.ui.InfoBubble({lat:coordinates.lat, lng: coordinates.lng}, {
            content: '<b>Hello World!</b>'
           });
    // show info bubble
    ui.addBubble(bubble);
}

setUpClickListener(map);
</script>

</body>
</html>

标签: javascriptmapshere-api

解决方案


map.removeObjects(map.getObjects ())

推荐阅读