Select to view content in your preferred language

ArcGIS Maps SDK for JavaScript API Map Development - Getting an Error

1286
6
Jump to solution
03-04-2026 02:17 PM
VenkataKondepati
Frequent Contributor

Hi Team,

I am building a Routing application and getting into an error message.

Failed to initialize map: Map failed to initialize within 20 seconds. Likely causes: invalid/expired ArcGIS API key, blocked ArcGIS network requests, or a basemap that could not load. Verify the API key in .env and confirm access to https://js.arcgis.com and ArcGIS basemap services. Diagnostics: view.ready=false, view.readyState=empty-map, view.updating=true, map.loadStatus=unknown, basemap.loadStatus=unknown

I understand that it is something to do with referrers configuration and added http://localhost:5173 but still getting an error. I have regenerated the key but no success.

Please refer the screenshot and let me know what I am I missing.

 

 

Regards,
Venkat
Book a meeting with me:Get on a Call
Follow me on: LinkedIn

If this response helps or is the solution to your post, please consider marking it as a solution
0 Kudos
2 Solutions

Accepted Solutions
TJSimons
Esri Contributor

Hi @VenkataKondepati - This is likely not related to a referrer.  Particularly if you did not have a referrer on the API Key to begin with.  Do you have screenshots of the console errors you are seeing? Could you share a code sample?  Feel free to contact Support and we can take a closer look.  https://support.esri.com/en-us/contact

View solution in original post

VenkataKondepati
Frequent Contributor

HI @TJSimons,

I have submitted the ticket as you requested. The support engineer had a session to review the issue and able to reproduce the issue from her side. I will keep you posted how it will go. 

Regards,
Venkat
Book a meeting with me:Get on a Call
Follow me on: LinkedIn

If this response helps or is the solution to your post, please consider marking it as a solution

View solution in original post

0 Kudos
6 Replies
TJSimons
Esri Contributor

Hi @VenkataKondepati - This is likely not related to a referrer.  Particularly if you did not have a referrer on the API Key to begin with.  Do you have screenshots of the console errors you are seeing? Could you share a code sample?  Feel free to contact Support and we can take a closer look.  https://support.esri.com/en-us/contact

VenkataKondepati
Frequent Contributor
// MapService for ArcGIS map initialization and management
// Implements Requirements 1.1, 1.2, 1.5

import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import esriConfig from '@arcgis/core/config'
import type Layer from '@arcgis/core/layers/Layer'

/**
 * Error thrown when map initialization fails
 */
export class MapInitializationError extends Error {
  constructor(message: string) {
    super(message)
    this.name = 'MapInitializationError'
  }
}

/**
 * MapService interface as defined in the design document
 */
export interface IMapService {
  initialize(container: HTMLDivElement, apiKey: string): Promise<MapView>
  setBasemap(basemapId: string): void
  setCenter(longitude: number, latitude: number): void
  setZoom(level: number): void
  addLayer(layer: Layer): void
  removeLayer(layerId: string): void
  destroy(): void
}

/**
 * Valid zoom level range
 * Requirement 1.5: Support zoom levels from street view (~18) to regional (~4)
 */
export const MIN_ZOOM = 4  // Regional overview
export const MAX_ZOOM = 18 // Street view

/**
 * Default map configuration
 */
export const DEFAULT_BASEMAP = 'streets-navigation-v2'
export const DEFAULT_CENTER = { longitude: -98.5795, latitude: 39.8283 } // Center of USA
export const DEFAULT_ZOOM = 10
export const MAP_INITIALIZATION_TIMEOUT_MS = 20000

/**
 * MapService implementation
 * Manages ArcGIS MapView initialization and layer management
 */
export class MapService implements IMapService {
  private map: Map | null = null
  private view: MapView | null = null
  private initialized = false

  private buildDiagnostics(): string {
    const map = this.map
    const view = this.view
    const basemap = map?.basemap

    const details = [
      `view.ready=${String(view?.ready ?? false)}`,
      `view.readyState=${String(view?.readyState ?? 'unknown')}`,
      `view.updating=${String(view?.updating ?? 'unknown')}`,
      `map.loadStatus=${String(map?.loadStatus ?? 'unknown')}`,
      `basemap.loadStatus=${String(basemap?.loadStatus ?? 'unknown')}`,
    ]

    const fatalError = view?.fatalError
    const mapLoadError = map?.loadError
    const basemapLoadError = basemap?.loadError

    if (fatalError instanceof Error) {
      details.push(`view.fatalError=${fatalError.message}`)
    }

    if (mapLoadError instanceof Error) {
      details.push(`map.loadError=${mapLoadError.message}`)
    }

    if (basemapLoadError instanceof Error) {
      details.push(`basemap.loadError=${basemapLoadError.message}`)
    }

    return details.join(', ')
  }

  private buildTimeoutMessage(): string {
    const timeoutSeconds = Math.floor(MAP_INITIALIZATION_TIMEOUT_MS / 1000)
    const diagnostics = this.buildDiagnostics()

    const guidance = [
      `Map failed to initialize within ${timeoutSeconds} seconds.`,
      'Likely causes: invalid/expired ArcGIS API key, blocked ArcGIS network requests, or a basemap that could not load.',
      'Verify the API key in .env and confirm access to https://js.arcgis.com and ArcGIS basemap services.',
    ]

    return `${guidance.join(' ')} Diagnostics: ${diagnostics}`
  }

  /**
   * Initialize the ArcGIS MapView with API key validation
   * Validates: Requirement 1.1 (initialize with valid API key)
   * Validates: Requirement 1.2 (display base map with street-level detail)
   */
  async initialize(container: HTMLDivElement, apiKey: string): Promise<MapView> {
    // Validate API key
    if (!apiKey || typeof apiKey !== 'string' || apiKey.trim() === '') {
      throw new MapInitializationError('Invalid ArcGIS API key. Please check configuration.')
    }

    // Validate container
    if (!container || !(container instanceof HTMLDivElement)) {
      throw new MapInitializationError('Invalid container element. Must be an HTMLDivElement.')
    }

    // Set the API key in ArcGIS config
    esriConfig.apiKey = apiKey.trim()

    try {
      // Create the map with a street-level basemap suitable for route visualization
      this.map = new Map({
        basemap: DEFAULT_BASEMAP,
      })

      // Create the MapView
      this.view = new MapView({
        container,
        map: this.map,
        center: [DEFAULT_CENTER.longitude, DEFAULT_CENTER.latitude],
        zoom: DEFAULT_ZOOM,
        constraints: {
          minZoom: MIN_ZOOM,
          maxZoom: MAX_ZOOM,
        },
      })

      // Wait for the view to be ready, but fail fast if ArcGIS never resolves.
      await Promise.race([
        this.view.when(),
        new Promise<never>((_, reject) => {
          window.setTimeout(() => {
            reject(
              new MapInitializationError(
                this.buildTimeoutMessage()
              )
            )
          }, MAP_INITIALIZATION_TIMEOUT_MS)
        }),
      ])
      
      this.initialized = true
      return this.view
    } catch (error) {
      // Clean up on failure
      this.destroy()
      
      const message = error instanceof Error ? error.message : 'Unknown error'
      throw new MapInitializationError(`Failed to initialize map: ${message}`)
    }
  }

  /**
   * Change the basemap
   * Validates: Requirement 1.2 (display base map)
   */
  setBasemap(basemapId: string): void {
    this.ensureInitialized()
    
    if (!basemapId || typeof basemapId !== 'string') {
      throw new Error('Invalid basemap ID')
    }

    this.map!.basemap = basemapId as __esri.BasemapProperties['basemap']
  }

  /**
   * Set the map center point
   */
  setCenter(longitude: number, latitude: number): void {
    this.ensureInitialized()
    
    // Validate coordinates
    if (longitude < -180 || longitude > 180) {
      throw new Error('Longitude must be between -180 and 180')
    }
    if (latitude < -90 || latitude > 90) {
      throw new Error('Latitude must be between -90 and 90')
    }

    this.view!.center = [longitude, latitude]
  }

  /**
   * Set the map zoom level
   * Validates: Requirement 1.5 (support zoom levels from street view to regional)
   */
  setZoom(level: number): void {
    this.ensureInitialized()
    
    // Validate zoom level
    if (level < MIN_ZOOM || level > MAX_ZOOM) {
      throw new Error(`Zoom level must be between ${MIN_ZOOM} and ${MAX_ZOOM}`)
    }

    this.view!.zoom = level
  }

  /**
   * Add a layer to the map
   */
  addLayer(layer: Layer): void {
    this.ensureInitialized()
    
    if (!layer) {
      throw new Error('Layer is required')
    }

    this.map!.add(layer)
  }

  /**
   * Remove a layer from the map by ID
   */
  removeLayer(layerId: string): void {
    this.ensureInitialized()
    
    if (!layerId || typeof layerId !== 'string') {
      throw new Error('Layer ID is required')
    }

    const layer = this.map!.findLayerById(layerId)
    if (layer) {
      this.map!.remove(layer)
    }
  }

  /**
   * Clean up resources
   */
  destroy(): void {
    if (this.view) {
      this.view.destroy()
      this.view = null
    }
    
    if (this.map) {
      this.map.destroy()
      this.map = null
    }
    
    this.initialized = false
  }

  /**
   * Get the current MapView instance
   */
  getView(): MapView | null {
    return this.view
  }

  /**
   * Get the current Map instance
   */
  getMap(): Map | null {
    return this.map
  }

  /**
   * Check if the service is initialized
   */
  isInitialized(): boolean {
    return this.initialized
  }

  /**
   * Ensure the service is initialized before operations
   */
  private ensureInitialized(): void {
    if (!this.initialized || !this.map || !this.view) {
      throw new Error('MapService is not initialized. Call initialize() first.')
    }
  }
}

// Export a singleton instance for convenience
export const mapService = new MapService()
Regards,
Venkat
Book a meeting with me:Get on a Call
Follow me on: LinkedIn

If this response helps or is the solution to your post, please consider marking it as a solution
0 Kudos
VenkataKondepati
Frequent Contributor

Hi @TJSimons,

Thanks for the response. 
Please find the attached screenshot.

Regards,
Venkat
Book a meeting with me:Get on a Call
Follow me on: LinkedIn

If this response helps or is the solution to your post, please consider marking it as a solution
0 Kudos
TJSimons
Esri Contributor

Hi @VenkataKondepati - I recommend logging a case with Support, https://support.esri.com/en-us/contact.  We will be able to look at this more closely with you.   

0 Kudos
VenkataKondepati
Frequent Contributor

HI @TJSimons,

I have submitted the ticket as you requested. The support engineer had a session to review the issue and able to reproduce the issue from her side. I will keep you posted how it will go. 

Regards,
Venkat
Book a meeting with me:Get on a Call
Follow me on: LinkedIn

If this response helps or is the solution to your post, please consider marking it as a solution
0 Kudos
VenkataKondepati
Frequent Contributor

This issue is fixed. It is a code issue which is generated by Codex Agent.

Regards,
Venkat
Book a meeting with me:Get on a Call
Follow me on: LinkedIn

If this response helps or is the solution to your post, please consider marking it as a solution
0 Kudos