javascriptgoogle-mapsdrawingimport-libraries

Using google.maps.importLibrary API, Want To Add A Circle Around PIN


I have seen API calls that do not use the Import Library method.

Like:

cityCircle = new google.maps.Circle(sunCircle);
cityCircle.bindTo('center', marker, 'position');

But I am using the Import Library.

Everything else works in my code but the circle.

I get Error: The library circle is unknown.

I follow the link it recommends. I do not know whether to use drawing or geometery.

Using the search on api documentation for circle radius never shows anything involving importing library.

I appreciate any guidance.

My Code that creates the PIN. This is inside an object ModGPS (attempting some resemblance To OOP.)

    PinIt : async function ( sComp, sName, nLat, nLon, nRadius, sFunc = 'PinIt' )
    {
        if ( ModGPS.debug )    console.log( ModGPS.Object + '    ' + sFunc + '()' ) ;
        
        const { Map } = await google.maps.importLibrary( "maps" ) ;
        const { Marker } = await google.maps.importLibrary( "marker" ) ;
        const { Circle } = await google.maps.importLibrary( "circle" ) ;
        
        let oPosition = { lat : nLat, lng : nLon, } ;
        
        let oCoord =
        {
            zoom   : 18,
            center : oPosition ,
            mapId  : 'Company_Properties',
        } ;
        
        let NewMap = new Map( ModGPS.dom.Map, oCoord ) ;
        
        let sDisplay = ".\n \n      " + sComp + "   " + sName + "      \n \n." ;
        
        const marker = new Marker( { map : NewMap, position : oPosition, title : sDisplay, } ) ;
        
        const circle = new Circle(
            {
                strokeColor   : "#FF0000",
                strokeOpacity : 0.8,
                strokeWeight  : 2,
                fillColor     : "#FF0000",
                fillOpacity   : 0.35,
                NewMap,
                center        : oPosition,
                radius        : nRadius,
            }
        ) ;
    },

Solution

  • The Circle class is still within the "maps" library

    There's no such thing as "circle" library in the API. As I can see in your code, you are trying to import the Circle class in this way:

    const { Circle } = await google.maps.importLibrary("circle")
    

    Please note that there's nothing on the official documentation which says that this is how you import the Circle class.

    If you go to the Circle Class section in the Reference Documentation, you can access the class by calling,

    const {Circle} = await google.maps.importLibrary("maps")
    

    This means that the Circle class is still included within the "maps" core library. And that the "circle" library you used as an argument to .importLibrary is non-existent as described by the error you encountered:

    Error: The library circle is unknown

    Here's a sample code snippet for you to see it working fine with the mentioned solution above:

    // Initialize and add the map
    let map;
    
    async function initMap() {
      // The location of Uluru
      const position = { lat: -25.344, lng: 131.031 };
      // Request needed libraries.
      //@ts-ignore
      const { Map } = await google.maps.importLibrary("maps");
      const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
      // This is how you correctly import the Circle class
        const { Circle } = await google.maps.importLibrary("maps");
    
      // The map, centered at Uluru
      map = new Map(document.getElementById("map"), {
        zoom: 4,
        center: position,
        mapId: "DEMO_MAP_ID",
      });
    
      // The marker, positioned at Uluru
      const marker = new AdvancedMarkerElement({
        map: map,
        position: position,
        title: "Uluru",
      });
        
      // instantiating the circle here:
        const circle = new Circle({
            center: position,
            radius: 1000000,
            map: map,
        })
    }
    
    
    
    initMap();
    /**
     * @license
     * Copyright 2019 Google LLC. All Rights Reserved.
     * SPDX-License-Identifier: Apache-2.0
     */
    /* 
      * Always set the map height explicitly to define the size of the div element
      * that contains the map. 
      */
    #map {
      height: 100%;
    }
    
    /* Optional: Makes the sample page fill the window. */
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <!DOCTYPE html>
    <!--
      @license
      Copyright 2019 Google LLC. All Rights Reserved.
      SPDX-License-Identifier: Apache-2.0
    -->
    <html>
      <head>
        <title>Simple Polygon</title>
        <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
      </head>
      <body>
        <div id="map"></div>
    <script>
      (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
        key: "AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk",
        v: "weekly",
        // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.).
        // Add other bootstrap parameters as needed, using camel case.
      });
    </script>
      </body>
    </html>

    I hope this helps!