'JavaScript Google Map API: add marker to the map without new a google.maps.Map object

I found that every time I want to add marker to the map, I have to new a map, which cost money.

So I tried to define map outside function.

The pseudocode looks like this

var map;
function initMap(robot_pos) {
    map = new google.maps.Map(document.getElementById("map"), {
        center: robot_pos,
        zoom: 20,                 // 0 ~ 22
        zoomControl: false,         // Zoom control UI at bottom right (with + - icon)
        gestureHandling: "none",    // Including panning, zooming with mouse event (dragging, scrolling, ...)
        streetViewControl: false,   // Street view UI at bottom right (with a yellow human icon)
        keyboardShortcuts: false,   // Keyboard short cut to interact with map (zooming, panning, ...)
        fullscreenControl: false,   // Full screen UI at top right
        clickableIcons: false,      // The icon on the map
        mapTypeControl: false,
        mapTypeId: 'hybrid'
    });
    console.log("initMap:", map);
}

function Draw_google_map(
    robot_pos,
    anomaly_pos,
    route,
    center,
    zoom) {
    /*
    API Reference: https://developers.google.com/maps/documentation/javascript/reference
    */
    console.log("Draw map: ", map);
    const robot = new google.maps.Marker({
        position: robot_pos,
        title:"Robot"
    });

    const anomaly = new google.maps.Marker({
        position: anomaly_pos,
        title:"Anomaly"
    });

    const polyline = new google.maps.Polyline({
        path: route,
        geodesic: true,
        strokeColor: "#FF0000",
        strokeOpacity: 1.0,
        strokeWeight: 2,
    });
    robot.setMap(map);
    anomaly.setMap(map);
    polyline.setMap(map);
}

The first time entering this function, init is true, so the map will call the function to new google.maps.Map

If the second time I want to call this function, the map seems to crash on the website.

I try to console.log the difference of the different timing of the map object

The only difference is the renderingType. When I new the map object, it is UNINITIALIZED; after I new it, and reference the map again, it becomes RASTER

So I'm wondering if there's a way to just initialize the map only once?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source