Resolving the Uncaught TypeError Issue in Your Javascript Openlayers Application

I am encountering some challenges with a JavaScript and OpenLayers integration.

My current code structure is as follows:

   <!-- OpenLayers Example  -->
<!DOCTYPE html>
<html>
<head>
    <title>OpenLayers Example</title>
    <!-- Styles for example -->
    <link rel="stylesheet" href="https://playground.fmeserver.com/css/FMEServerExamples.css" type="text/css" />
    <!-- Include FMEServer.js -->
    <script type="text/javascript" src="https://api.fmeserver.com/js/v3/FMEServer.js"></script>
    <!-- The following are Required for OpenLayers -->
    <script type="text/javascript" src="https://openlayers.org/api/OpenLayers.js"></script>
    <!--Open Layers-->
    <script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
    <style>
      #map { 
        width: 1500px;
        height: 800px;
        border: 1px solid black;
      }
    </style>
</head>
<body>
    <h4>This example clips data to a user drawn polygon.</h4>
    <form id="exampleForm">
        <label><b>Step 1</b> - Draw the Polygon (Double Click to Close): </label>
        <input id="draw" type="button" value="Draw" />
        <input id="reset" type="button" value="Reset" /><br />
        <div id="map" class="map"></div>

        <label><b>Step 2</b> - Submit the Request to FME Server: </label>
        <input type="button" onclick="processClip();" value="Clip Data To Area" />
    </form>
<script type="text/javascript">

        var drawControl, mouseControl, polygonLayer, map;
        var clippingGeometry = [];

    window.onload = function() {

      var map = new ol.Map({
        target: 'map',
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
        view: new ol.View({
          center: ol.proj.fromLonLat([11.974044, 57.708682]),
          zoom: 12
        })
      });

      // Layer from Geoserver
        var Geoserver_WMS = new ol.layer.Tile({
            title: "Test Geoserver",
            source: new ol.source.TileWMS({
                url: '*URLGoesHere*',
                params: {
                    'LAYERS': '*LayerGoesHere*', 'TILED': true,
                    'STYLES': ''
                },
                serverType: 'geoserver',
                projection: ol.proj.get('EPSG:3007'),
            })
        });

        map.addLayer(Geoserver_WMS);

        document.getElementById( "draw" ).setAttribute( "onclick", "drawPolygon();" );
        document.getElementById( "reset" ).setAttribute( "onclick", "drawReset();" );

        FMEServer.init({
            server : "https://demos-safe-software.fmecloud.com",
            token : "568c604bc1f235bbe137c514e7c61a8436043070"

        });
    };

        function drawPolygon() {
            drawReset();

            polygonLayer = new OpenLayers.Layer.Vector( "Polygon Layer" );
            mouseControl = new OpenLayers.Control.MousePosition();

            map.addLayer( polygonLayer );
            map.addControl( mouseControl );

            drawControl = new OpenLayers.Control.DrawFeature( polygonLayer,
                OpenLayers.Handler.Polygon );
            map.addControl( drawControl );
            drawControl.activate();
        }

        function drawReset() {
            if( drawControl ) {
                map.removeLayer( polygonLayer );
                polygonLayer = null;
                mouseControl.deactivate();
                mouseControl = null;
                drawControl.deactivate();
                drawControl = null;
                clippingGeometry = [];
            }
        }

        function extractShape() {
            if( polygonLayer.features[0] ) {
                var vertices = polygonLayer.features[0].geometry.getVertices();
                for( var i = 0; i < vertices.length; i++ ) {
                    var point = vertices[i].transform( toProjection, fromProjection );
                    clippingGeometry.push( [ point.x, point.y ] );
                }
                clippingGeometry.push( clippingGeometry[0] );
                return true;
            }
            return false;
        }

        function showResults( json ) {
            // Write out the full return object for visualization
            var hr = document.createElement( "hr" );
            var div = document.createElement( "div" );

            // Extract the download link to the clipped data
            var download = json.serviceResponse.url;

            div.innerHTML = "<h4>Return Object:</h4><pre>"+JSON.stringify(json, undefined, 4)+"</pre>";
            div.innerHTML += "<hr><a href=\""+download+"\">Download Result</a>";
            document.body.appendChild( hr );
            document.body.appendChild( div );
        }

        function processClip() {
            var repository = "REST-Playground";
            var workspace = "WKTClip.fmw";

            if( extractShape() ) {

                // Process the clippingGeometry into a WKT Polygon string
                var geometry = "POLYGON((";

                for( var i = 0; i < clippingGeometry.length; i++ ) {
                    var lat = clippingGeometry[i][1];
                    var lng = clippingGeometry[i][0];
                    geometry += lng+" "+lat+",";
                }

                // Remove trailing , from string
                geometry = geometry.substr( 0, geometry.length - 1 );
                geometry += "))";

                // Set parameters for the Data Download Service (ESRI Shapefile Format)
                // FORMAT OPTIONS: ACAD, SHAPE, GML, OGCKML
                var params = "GEOM="+geometry+"&FORMAT=SHAPE";

                // Use the FME Server Data Download Service
                FMEServer.runDataDownload( repository, workspace, params, showResults );
            }
        }

    </script>
</body>
</html>

After clicking on "Draw," I encounter the following Error-message:

Uncaught TypeError: Cannot read property 'addLayer' of undefined

The expected functionality should allow me to obtain coordinates and draw a polygon, but unfortunately, it seems to be malfunctioning.

If anyone can identify the issue within the code, your insights would be greatly appreciated as I am struggling to pinpoint the problem, causing significant frustration. Thank you in advance for any suggestions.

Answer №1

A globally scoped map variable and a locally scoped one are present in your code. However, due to the current setup, the global variable is never assigned a value, leading to it always being undefined. This results in an error message.

Here's how you can modify the code:

window.onload = function() {

      var map = new ol.Map({
        target: 'map',
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
        view: new ol.View({
          center: ol.proj.fromLonLat([11.974044, 57.708682]),
          zoom: 12
        })
      });

Simply remove the var:

window.onload = function() {

      map = new ol.Map({
        target: 'map',
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
        view: new ol.View({
          center: ol.proj.fromLonLat([11.974044, 57.708682]),
          zoom: 12
        })
      });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Saving components locally (vue2)

Looking for help with passing data from Props to Data in vue.js? Check out this Stack Overflow discussion. If you're running into issues, take a look at this sandbox example: https://codesandbox.io/s/u3mr8. Concerned about side effects of copying ob ...

Encountering Internal Server Error when C# WebMethod communicates with JavaScript AJAX call

I've encountered an issue where my AJAX call to a C# WebMethod is not returning the expected result. Instead, it keeps showing an "Internal Server Error" message. A button triggers a JavaScript function: <button id="btn" onclick="Create();">fo ...

Adding a property conditionally in jsx: A guide

I have a simple example of Material UI RadioGroup code that I want to display conditionally in either a row or column format. By default, it is displayed in column format. Below is the code snippet: <RadioGroup aria-label="gender" name=&q ...

Issues with functionality in Bootstrap tabs are causing them to not operate

I am encountering an issue with bootstrap tabs. On the bootstrap tabs links, I have added my page ID before the #link. It works fine from ID 1 to 9, but after ID 10 and above, it shows an error page not found. Here is how the browser behaves: If I click on ...

Order of execution for Angular 2 components

import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; import {Router, ActivatedRoute, Params} from '@angular/router'; import { Country } from &ap ...

No data is being returned by the Jquery Ajax function

I am experiencing an issue with a Jquery Ajax call in my code: $('body').on('click', '#btnPopulate', function() { alert(getTree()); }); function getTree() { var url = getUrlPath() + "/StoryboardAdmin/BuildStoryboardViewMode ...

You can update a JavaScript string by adding values using the '+=' operator

I have the following function: function generateJSONstringforuncheckedfilters(){ jsonstring = ''; jsonstring = "["; $('body').on('click', 'input', function(){ jsonstring += "[{'OrderGUID&apo ...

Encountering issues with configuring an Express server with HTTPS

Having difficulty setting up my Express server on HTTPS and accessing my API. Below is the code I am using: // server.js const express = require('express'); const { readFileSync } = require('fs'); const https = require('https' ...

Saving HTML code entered in a textarea field does not work with the database

Recently, I encountered an issue on my website related to storing news posts in HTML format. My initial approach was to write the posts in HTML for better presentation and then transfer this code into a Textarea element. The plan was to save this input in ...

What is the reason that the for loop updates all indexes in Node.js?

Currently, I am working on a space battle program that involves nested arrays. In order to simulate fleet fighting, I have written the following code: //Roll a dice function const randomNumber = (number) => { return Math.floor(Math.random() * numbe ...

javascript doesn't execute the php script

Hello everyone, I've been working on a project for quite some time and I’ve encountered an issue that I can't seem to solve. Hopefully, you can help me out with this. I have a digital LED strip controlled by an Arduino, which in turn is control ...

Retrieving information upon page loading and setting it as select options within a Vue JS environment

Currently, I am working on a straightforward form that includes a select type form. This specific form is initially created without any options as I intend to dynamically populate them from the backend later. Below is the code snippet for reference: < ...

Suggestions for securely storing data on an iOS device using React Native?

I'm considering building an iOS app to store sensitive data, but I'm not sure where to start. Would AsyncStorage be a secure option for this purpose? ...

Access the Ajax response and store it in a JavaScript variable

I've successfully created a script that inserts data into an MySQL database using a modal and AJAX. However, I'm having trouble retrieving the response to complete an input field. Below is my current script: $.ajax({ url:"insertar_cl ...

Submit a list of checkboxes selected to Google Sheets separated by commas

Is there a way to modify the script I'm using to enter data from an HTML form into a Google Sheet so that my checkbox fields will be entered as a list, separated by commas? If all boxes were checked in the example form below, I would like the cell fo ...

Comparing $.fn.fancybox and $.fancybox: What sets them apart?

I'd like to understand the distinction between the two items shown above. In what ways do they differ from each other? ...

Is there a way to display only the specific child div within the parent div using JavaScript without affecting the others?

   **** Sorry for the lengthy title **** Today I encountered a problem that I would like to discuss with all of you. When I click on a "COMMENT" button, instead of triggering JavaScript code to display a CHILD.div inside the corresponding ...

Encountering permission issues while attempting to add `@nuxtjs/sentry` in a Docker container running Node 16.14. Installation

While attempting to add @nuxtjs/sentry to my project by running npm install @nuxtjs/sentry, I encountered some issues. Here is the error message I received: npm ERR! code 1 npm ERR! path /app/node_modules/@sentry/cli npm ERR! command failed npm ERR! comm ...

Creating a one-page application using knockout.js: Step-by-step guide

When it comes to organizing view-model classes, do you prefer separate classes or one large one? If opting for a giant class, how do you go about modularizing it? Additionally, what is your preferred method for switching between 'pages' while uti ...

Delay reading body until npm request completes

My current challenge involves using npm request and cheerio to extract webpages and analyze their HTML structure. Everything works smoothly in scenarios where the HTML is available upon request. However, I am facing a problem when a website initially displ ...