Search code examples
javascripthtmlcssopenlayers

javascript sode for mouse position display and Geolocation with openlayer and geocodezip example


I want to combine Geolocation and Mouse Position Display (lng/lat; outside of map)from the Openlayer and geocodezip site.I tried various combinations of codes But only the Mouse Position Display (lng/lat; outside of map) is correct.Geolocation does not work.In fact, both of them do not work together. This is the code I've tested the last time. please guide me.Thanks.

<!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>


Solution

  • There's an error in your code "Uncaught ReferenceError: view is not defined". In line projection: view.getProjection() the variable view is not defined.

    Not sure if view needs to be a global variable but if you define it outside the function then the location API is consumed. Jsfiddle here

    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 view = new ol.View({
      center: [0, 0],
      zoom: 2
    });
    
    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
    });
    
    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]
      })
    });
    <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>
    
    
    <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>