Search code examples
javascriptopenlayersnominatim

Error in OpenLayers when I try to change the map view


I'm trying to get started doing geocoding with OpenLayers and Nominatim, but when I try to change the view of the map (say, because the user entered an address and I want to center of the map on it) I get an error:

ol-debug.js:6171 Uncaught TypeError: Cannot read property 'getCode' of null
at Object.ol.proj.getTransformFromProjections (ol-debug.js:6171)
at Object.ol.proj.getTransform (ol-debug.js:6155)
at Object.ol.proj.transform (ol-debug.js:6251)
at Object.ol.proj.fromLonLat (ol-debug.js:6063)
at Object.<anonymous> ((index):74)
at c (jquery-3.4.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.4.1.min.js:2)
at l (jquery-3.4.1.min.js:2)
at XMLHttpRequest.<anonymous> (jquery-3.4.1.min.js:2)

Here is my code (mostly just mashed up sample code I found online):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>OpenStreetMap &amp; OpenLayers - Marker Example</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
    <script src="https://openlayers.org/en/v4.6.5/build/ol-debug.js" type="text/javascript"></script>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"
            integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
            crossorigin="anonymous"></script>

    <script>
        /* OSM & OL example code provided by https://mediarealm.com.au/ */
        var map;
        var mapLat = -33.829357;
        var mapLng = 150.961761;
        var mapDefaultZoom = 10;
        var view = new ol.View({
            center: ol.proj.fromLonLat([mapLng, mapLat]),
            zoom: mapDefaultZoom
        })
        function initialize_map() {
            map = new ol.Map({
                target: "map",
                layers: [
                    new ol.layer.Tile({
                        source: new ol.source.OSM({
                            url: "https://a.tile.openstreetmap.org/{z}/{x}/{y}.png"
                        })
                    })
                ],
                view: view
            });
        }
        function add_map_point(lat, lng) {
            var vectorLayer = new ol.layer.Vector({
                source: new ol.source.Vector({
                    features: [new ol.Feature({
                        geometry: new ol.geom.Point(ol.proj.transform([parseFloat(lng), parseFloat(lat)], 'EPSG:4326', 'EPSG:3857')),
                    })]
                }),
                style: new ol.style.Style({
                    image: new ol.style.Icon({
                        anchor: [0.5, 0.5],
                        anchorXUnits: "fraction",
                        anchorYUnits: "fraction",
                        src: "https://upload.wikimedia.org/wikipedia/commons/e/ec/RedDot.svg"
                    })
                })
            });
            map.addLayer(vectorLayer);
        }

        function geocode() {
            var address = $("#address").val();

            console.log(address);

            var data = {
                "format": "json",
                "addressdetails": 1,
                "q": address,
                "limit": 1
            };
            $.ajax({
                method: "GET",
                url: "https://nominatim.openstreetmap.org",
                data: data
            })
                .done(function (msg) {
                    console.log(msg);
                    add_map_point(msg[0].lat, msg[0].lon);
                    view.center = ol.proj.fromLonLat(msg[0].lon, msg[0].lat);
                    });
        }
    </script>
</head>
<body onload="initialize_map();">
    <input type="text" id="address" />
    <button type="submit" id="submit" onclick="geocode();">Submit</button>
    <div id="map" style="width: 100vw; height: 100vh;"></div>
</body>
</html>

So I type an address or city or whatever in the text box and click the submit button - a red dot appears on the map at the location searched for, but the map does not center itself on that location; instead I get the error I described previously. What could be going wrong?

edit: replaced the view.center line with:

view.animate({
    center: ol.proj.fromLonLat([msg[0].lon, msg[0].lat]),
    duration: 2000});

and that made it do something - but it's centering in the middle of the ocean!


Solution

  • view.center should be view.setCenter()

    view.setCenter([ol.proj.fromLonLat(msg[0].lon, msg[0].lat]);
    

    If the lon/lat values are strings they will need to be converted to float

    view.setCenter([ol.proj.fromLonLat(parseFloat(msg[0].lon), parseFloat(msg[0].lat)]);
    

    You could also try

    view.animate({
        center: ol.proj.fromLonLat([parseFloat(msg[0].lon), parseFloat(msg[0].lat)]),
        duration: 2000});