Search code examples
reactjsopenlayers

How fix Interaction import error with open layers 6 in React.js


How can fix the import error from interaction in React.js.

Attempted import error: 'interaction' is not exported from 'ol' (imported as 'ol').

I do not know how can export it.

I'm getting to much problems to get the correct imports with ol and ol-ext anyone know how can fix it?

import React from 'react';
import 'ol/ol.css';
import 'ol-ext/dist/ol-ext.css';
import * as ol from 'ol';
import ol_PerspectiveMap from "ol-ext/map/PerspectiveMap";

const MapPerspective = () => {

    var layer = new ol.layer.Tile({ name: "OSM", source: new ol.source.OSM() });
    // The map
    var map = new ol_PerspectiveMap( {
        target: 'map',
        view: new ol.View({
            zoom: 15,
            center: [-237646.86, 4875851.77]
        }),
        interactions: ol.interaction.defaults(),
        layers: [layer]
    });

    map.setPerspective(30);

    map.on('change:perspective', function (e) {
        if (!e.animating) this('#angle').val(e.angle);
    })

    // Create vector layer for select
    var vectorSource = new ol.source.Vector({
        url: 'assets/dist/data/ignf.json',
        format: new ol_Format.GeoJSON(),
        attributions: ["&copy; <a href='http://professionnels.ign.fr/bdtopo'>ign.fr</a>"]
    });
    var vector = new ol.layer.VectorImage({
        source: vectorSource,
        maxResolution: 2
    });
    map.addLayer(vector);

    //   Select and draw interaction
    map.addInteraction(new ol.interaction.Select({
        layers: [vector],
        condition: function (e) {
            return (ol_Events.condition.pointerMove(e) && !ol_Events.condition.altKeyOnly(e))
        }
    }));
    map.addInteraction(new ol.interaction.Draw({ type: 'LineString' }))

    //   An overlay
    var place = new ol.overlay.Placemark({
        color: '#000',
        position: [-237646.86, 4875851.77],
        stopEvent: false
    });
    map.addOverlay(place);


Solution

  • When using es module, you must import each interaction like this:

    import { defaults } from 'ol/interaction';
    import Draw from 'ol/interaction/Draw';
    

    I suggest you do the same for all ol objects.

    Reading the doc could help you : https://openlayers.org/en/latest/apidoc/module-ol_interaction_Draw-Draw.html

    I did not test if it works in combination with ol-ext.