OpenLayers 3 Beginner’s Guide

Finding your mouse position

Open sample in a new windows

<!doctype html>
  <head>
    <title>Simple example</title>
    <link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
    <link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
  </head>
  <body>
    <div id="map" class="map"></div>
    <br/>
    <div id="myposition"></div>
    <script src="../assets/ol3/js/ol.js"></script>
    <script>
      var osm_default = new ol.layer.Tile({
        source: new ol.source.OSM()
      });

      var map = new ol.Map({
        layers: [osm_default],
        target: 'map',
        view: new ol.View({
          center: ol.proj.transform([-1.81185, 52.443141], 'EPSG:4326', 'EPSG:3857'),
          zoom: 6
        })
      });

      var mousePosition = new ol.control.MousePosition({
        coordinateFormat: ol.coordinate.createStringXY(2),
        projection: 'EPSG:4326',
        target: document.getElementById('myposition'),
        undefinedHTML: '&nbsp;'
      });

      map.addControl(mousePosition);
    </script>
  </body>
</html>