JavaScript code for displaying mouse positions and Geolocation using OpenLayers, along with a Geocodezip demonstration

I have attempted to merge Geolocation and Mouse Position Display (longitude/latitude; outside of map) from the OpenLayers and geocodezip site, but I am facing issues. The Mouse Position Display works correctly, however, Geolocation does not seem to work. Unfortunately, both features do not work together when combined. Below is the code that I last tested. Any guidance you can provide would be greatly appreciated. Thank you.

<!DOCTYPE html>
<html>
  <head>
    <title>Mouse Position and Geolocation</title>
<link rel="stylesheet" href="https://openlayers.org/en/v5.3.0/css/ol.css" type="text/css">
    <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList"></script>
    
    
    <script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
 
  </head>
  <body>
    <div id="map" class="map"></div>
    <div id="mouse-position"></div>
    <form>
      <label>Projection </label>
      <select id="projection">
        <option value="EPSG:4326">EPSG:4326</option>
        <option value="EPSG:3857">EPSG:3857</option>
      </select>
      <label>Precision </label>
      <input id="precision" type="number" min="0" max="12" value="6"/>
    </form>
<div id="info" style="display: none;"></div>
    <label for="track">
      track position
      <input id="track" type="checkbox"/>
    </label>
    <p>
positionshowingtouser: <code id="positionshowingtouser1"></code>&nbsp;&nbsp;
      position accuracy : <code id="accuracy"></code>&nbsp;&nbsp;
      altitude : <code id="altitude"></code>&nbsp;&nbsp;
      altitude accuracy : <code id="altitudeAccuracy"></code>&nbsp;&nbsp;
      heading : <code id="heading"></code>&nbsp;&nbsp;
      speed : <code id="speed"></code>
  resultTEST : <code id="resultTEST"></code>
    </p>
    <script>
      var mousePositionControl = new ol.control.MousePosition({
        coordinateFormat: ol.coordinate.createStringXY(6),
        //projection: 'EPSG:4326',
        // comment the following two lines to have the mouse position
        // be placed within the map.
        className: 'custom-mouse-position',
        target: document.getElementById('mouse-position'),
        undefinedHTML: '&nbsp;'
      });

      var map = new ol.Map({
        controls: ol.control.defaults({
          attributionOptions: {
            collapsible: true
          }
        }).extend([mousePositionControl]),
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
        target: 'map',
        view: new ol.View({
          center: [0, 0],
          zoom: 2
        })
      });

      var projectionSelect = document.getElementById('projection');
      projectionSelect.addEventListener('change', function(event) {
        mousePositionControl.setProjection(event.target.value);
      });

      var precisionInput = document.getElementById('precision');
      precisionInput.addEventListener('change', function(event) {
        var format = ol.coordinate.createStringXY(event.target.valueAsNumber);
        mousePositionControl.setCoordinateFormat(format);
      });
  var geolocation = new ol.Geolocation({
        // enableHighAccuracy must be set to true to have the heading value.
        trackingOptions: {
          enableHighAccuracy: true
        },
        projection: view.getProjection()
      });

      function el(id) {
        return document.getElementById(id);
      }

      el('track').addEventListener('change', function() {// addEventListener yek method javascripty koli ast
        geolocation.setTracking(this.checked);// setTracking yek method openlayeri ast ke meghdar boolian migirad
      });

      // update the HTML page when the position changes.
      geolocation.on('change', function() {
    el('positionshowingtouser1').innerText = geolocation.getPosition();
        el('accuracy').innerText = geolocation.getAccuracy() + ' [m]';
        el('altitude').innerText = geolocation.getAltitude() + ' [m]';
        el('altitudeAccuracy').innerText = geolocation.getAltitudeAccuracy() + ' [m]';
        el('heading').innerText = geolocation.getHeading() + ' [rad]';
        el('speed').innerText = geolocation.getSpeed() + ' [m/s]';

      });

      // handle geolocation error.
      geolocation.on('error', function(error) {
        var info = document.getElementById('info');
        info.innerHTML = error.message;
        info.style.display = '';
      });

      var accuracyFeature = new ol.Feature();
      geolocation.on('change:accuracyGeometry', function() {
        accuracyFeature.setGeometry(geolocation.getAccuracyGeometry());
      });

      var positionFeature = new ol.Feature();
      positionFeature.setStyle(new ol.style.Style({
        image: new ol.style.Circle({
          radius: 16,
          fill: new ol.style.Fill({
            color: '#FF0000'
          }),
          stroke: new ol.style.Stroke({
            color: '#fff',
            width: 2
          })
        })
      }));

      geolocation.on('change:position', function() {
        var coordinates = geolocation.getPosition();
        positionFeature.setGeometry(coordinates ?
          new ol.geom.Point(coordinates) : null);
      });

      new ol.layer.Vector({
        map: map,
        source: new ol.source.Vector({
          features: [accuracyFeature, positionFeature]
        })
      });
 
    </script>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"> 
</script> 
<script type="text/javascript"> 
_uacct = "UA-162157-1";
urchinTracker();
</script> 
  </body>
</html>

Answer №1

An issue has been identified in your code: "Uncaught ReferenceError: view is not defined". This error occurs on line projection: view.getProjection() where the variable view is not declared.

If you move the definition of view outside the function, it might resolve the problem as the location API may then be accessed. You can find a working example on Jsfiddle here

// Create and configure mousePositionControl
var mousePositionControl = new ol.control.MousePosition({
  coordinateFormat: ol.coordinate.createStringXY(6),
  //projection: 'EPSG:4326',
  // comment out the following two lines to have the mouse position
  // displayed within the map.
  className: 'custom-mouse-position',
  target: document.getElementById('mouse-position'),
  undefinedHTML: '&nbsp;'
});

// Define the view
var view = new ol.View({
  center: [0, 0],
  zoom: 2
});

// Create and configure map
var map = new ol.Map({
  controls: ol.control.defaults({
    attributionOptions: {
      collapsible: true
    }
  }).extend([mousePositionControl]),
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    })
  ],
  target: 'map',
  view: view
});

// Event listener for projection select change
var projectionSelect = document.getElementById('projection');
projectionSelect.addEventListener('change', function(event) {
  mousePositionControl.setProjection(event.target.value);
});

// Event listener for precision input change
var precisionInput = document.getElementById('precision');
precisionInput.addEventListener('change', function(event) {
  var format = ol.coordinate.createStringXY(event.target.valueAsNumber);
  mousePositionControl.setCoordinateFormat(format);
});
...
... // Remaining code snippet omitted for brevity
<link rel="stylesheet" href="https://openlayers.org/en/v5.3.0/css/ol.css" type="text/css">
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList"></script>
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>

... // Additional HTML markup omitted for brevity

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

Displaying a page with dynamic data fetched from the server-side to be utilized in the getInitialProps method of

As a newcomer to next.js, my goal for my project is to connect to a database, retrieve data, process it using express, and then utilize it on the client side of my application. I plan to establish a connection to the database within the express route han ...

Using router-links with events: A simple guide

My current issue involves passing information to another page. During testing without using routes, I was successful in passing information from one component to another. However, after implementing routes, clicking the event navigates to the other compo ...

Resolved navigation bar problems

As a beginner in web development, I am working hard to launch my first website. Today, I have a question for the stack overflow community regarding a fixed navbar issue. The navbar I have created is functioning properly on Chrome, but when it comes to Fire ...

Refresh the data in a table upon clicking the menu

I am looking to develop an accordion MENU, but unsure if I should use divs or <ul>. When a submenu is clicked, I want to execute a mysql query to update the data in the table next to the menu. I'm not sure of the best approach and whether to uti ...

Generating distinctive content within the confines of the Selenium WebDriver

Is there a way to generate a unique username value for the signup page username textbox using selenium webdriver instead of hardcoding it? For example: driver.findElement(By.id("username")).sendKeys("Pinklin") ; When "Pinklin" is hardcoded, running the ...

Can anyone help me get my carousel to work properly?

I am facing a carousel problem in my personal exercise project. I have gathered HTML, CSS, and JavaScript from the internet and am attempting to integrate them all together. //Sidebar script start $(document).ready(function () { var trigger = $(&apo ...

Date input using manual typing format

I've implemented the ng-pick-datetime package for handling date selection and display. By using dateTimeAdapter.setLocale('en-IN') in the constructor, I have successfully changed the date format to DD/MM/YYYY. However, I'm facing an iss ...

Encountering an issue in Typescript where utilizing ref in ShaderMaterial triggers an error stating: "The anticipated type is originating from the property 'ref' declared within the 'PolygonMat' type definition."

While working on a shaderMaterial with the drei library, I encountered an issue with TypeScript when using ref: Type 'RefObject<PolygonMat>' is not assignable to type 'Ref<ShaderMaterial> | undefined'. I defined the type ...

Integrate the user input data into a modal window using Bootstrap

Looking for a solution to a problem, I'm trying to implement a system on my website that sends messages to registered users. After creating a form with necessary information, clicking the send button should display a preview of the message before send ...

Creating a dynamic dropdown menu that changes based on the selection from another dropdown menu

I'm working on a project that requires users to make specific selections in dropdown menus that are interconnected. Does anyone know how to set up a form so that the options in dropdown menu #2 change based on what the user selects in dropdown menu #1 ...

Having trouble parsing a JSON string in your JavaScript code?

As a java developer transitioning to JavaScript, I'm faced with the task of parsing a JSON string retrieved from a WebService. Here is the JSON String: { "myArrayList": [ { "myHashMap": { "firstName": "Clara", ...

What is the best way to safely distribute the same npm package with multiple contributors?

Imagine a collaborative open source project with multiple contributors working on it. As the project progresses, these contributors need to publish their work to the NPM registry. But how can this be done securely when multiple people are involved? The ow ...

What could possibly be causing the notification to fail to function in my deferred scenario?

I'm currently delving into the world of jquery deferred and making good progress, but I have encountered a hurdle when it comes to the notify feature. In my code snippet, you will notice that I attempted to use the notify method, only to find out that ...

Unlike other templating engines, EJS does not automatically escape characters

In my current project, I am utilizing a Node JS server to query MongoDB and then display the results in an EJS template using the code snippet: res.render('graphFabric.ejs', {'iBeacons':[(beacon)]});. However, when attempting to re ...

Vue component's data remains stagnant within created() hook

I'm currently working on transforming the API response to make it more suitable for constructing two tables. Despite adding debugging outputs within my function in created(), I am witnessing the desired output temporarily, but upon further examination ...

The power of the V8 JavaScript engine: Understanding v8::Arguments and the versatility of function

I have created a Node.js addon that wraps a C++ standard library element std::map<T1,T2>. The goal is to expose this map as a module with two primary functions: Set for adding new key-value pairs and Get for retrieving values by key. I want to create ...

Ways to make JavaScript cycle through a set of images

I'm having trouble trying to set up a code that will rotate multiple images in a cycle for an image gallery I'm working on. So far, I've only been able to get one image to cycle through successfully. Any help or suggestions would be greatly ...

Div content with a unique angle

I need to create a website with slanted div elements that must meet the following criteria: The sections should have a height of approximately 400px when displayed side by side, and about 800px when they stack vertically. It would be ideal if this could ...

Customize the DOM with tailwind CSS in a Vanilla JavaScript project

I am attempting to hide the "mark as complete" button and replace it with a "completed" button by switching the classes from "hidden" to "completed" and vice versa. However, when I use an event listener to manipulate the DOM with the code provided below, t ...

Bringing in a script and invoking a function on a specific variable

As a newcomer to Typescript, I've been experimenting with some code I came across online to enhance the appearance of links on my website. <script src="https://wow.zamimg.com/widgets/power.js"></script> <script>var wowhead_tooltips ...