添加默认地图事件时抛出"map instance required"错误
Yes, I was able to reproduce your error right away when testing your code. The root cause is duplicate loading of HERE Maps core libraries in your HTML head section.
Looking at your script imports:
- You've included
mapsjs-core.jstwice - You've included
mapsjs-service.jstwice
When the second instance of these libraries loads, it resets the global H object that HERE Maps relies on. This means the map instance you created before the second library load is no longer recognized as a valid instance by the newly loaded H.mapevents.MapEvents constructor—hence the "map instance required" error.
Fixed Code
Here's your corrected HTML with duplicate imports removed:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>HERE Map Mouse Pan Test</title> <script src="https://js.api.here.com/v3/3.1/mapsjs-core.js" type="text/javascript" charset="utf-8"></script> <script src="https://js.api.here.com/v3/3.1/mapsjs-service.js" type="text/javascript" charset="utf-8"></script> <script src="https://js.api.here.com/v3/3.1/mapsjs-ui.js" type="text/javascript" charset="utf-8"></script> <script src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js" type="text/javascript" charset="utf-8"></script> <link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.1/mapsjs-ui.css" /> </head> <body> <div id="map" style="height: 500px; width: 500px;"></div> <script> var platform = new H.service.Platform({ 'apikey': 'REPLACED' }); var defaultLayers = platform.createDefaultLayers(); var mapElement = document.getElementById('map'); var map = new H.Map( mapElement, defaultLayers.vector.normal.map, { zoom: 5, center: { lat: 0, lng: 0 }, pixelRatio: window.devicePixelRatio || 1 } ); console.log(map); var ui = H.ui.UI.createDefault(map, defaultLayers); var mapEvents = new H.mapevents.MapEvents(map); var behavior = new H.mapevents.Behavior(mapEvents); </script> </body> </html>
Key Fixes
- Removed the duplicate
mapsjs-core.jsandmapsjs-service.jsscript tags - Added a semicolon after the
mapconstructor (optional but good practice to avoid unexpected behavior)
After applying these changes, the mouse pan behavior should work as expected, and the error will no longer appear.
内容的提问来源于stack exchange,提问作者Throwaway135237

