Google Maps API - Polygon From Coordinates

From NoskeWiki
Jump to navigation Jump to search
Drawing polygon from lat/lngs".

About

NOTE: This page is a daughter page of: Google Maps API


This piece of code demonstrates the drawing of a polygon based on lat,lng pairs in a text area... and also the adding of a single marker with a click listener.


Drawing a Polygon from Coordinates

<!DOCTYPE html>
<html>
  <head>
    <meta name='viewport' content='initial-scale=1.0, user-scalable=no'>
    <meta charset='utf-8'>
    <title>Draw Polygon from Text Area</title>
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
      textarea {
        vertical-align: top;
        font-size: 90%;
      }
      #btn-geocode {
        vertical-align: top;
      }
      #panel {
        position: absolute;
        top: 5px;
        left: 50%;
        margin-left: -400px;
        z-index: 5;
        background-color: #fff;
        padding: 5px;
        border: 1px solid #999;
      }
    </style>
    <script src='https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true'></script>
    <script>
/**
 * Script which reads in a text area with lat,lng
 * pairs and draws a polygon. To help the user draw
 * new polygons, the user can also click to move around
 * a single marker around and it reports the coordinates. 
 */
var myPolygon;
var myMarker;
var map;


/**
 * Initializes map and adds click listener.
 */
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 5,
    center: {lat: 28, lng: 88.5},  // Near Mount Everest.
    mapTypeId: google.maps.MapTypeId.TERRAIN
  });

  google.maps.event.addListener(map, 'click', function(event) {
    placeMarker(event.latLng);
  });
}


/**
 * Changes the location of the marker, and updates a text box
 * ('txt-marker-coord') show the new lat,lng.
 * param@ {google.maps.LatLng} location The lat,lng of user click.
 */
function placeMarker(location) {
  if (myMarker == undefined) {
    myMarker = new google.maps.Marker({
      position: location,
      map: map,
      animation: google.maps.Animation.DROP,
    });
  } else {
    myMarker.setPosition(location);
  }
  document.getElementById('txt-marker-coord').value =
      location.lat().toFixed(5) + ',' + location.lng().toFixed(5);
}


/**
 * Reads in a text area ('txt-coords') and parses it for a series
 * of newline separated lat,lng coordinates. The final polygon
 * is then rendered onto the map.
 */
function updatePoygon() {
  // If polygon already added to map, remove it:
  if (myPolygon) {
    myPolygon.setMap(null);
  }

  // Parse text area and create polygon coordinates:
  var coordText = document.getElementById('txt-coords').value;
  var lines = coordText.split('\n');

  var polygonCoords = [];
  for (var i = 0; i < lines.length; i++) {
    var line = lines[i];
    var coordParts = line.split(',');
    if (coordParts.length != 2) {
      window.alert('Error on line ' + (i+1) + ' (' + line + ') ' +
                   '... each line should look like "40,30" (lat,lng).');
      return;
    }
    var newLat = parseFloat(coordParts[0]);
    var newLng = parseFloat(coordParts[1]);
    var finalCoord = { lat: newLat, lng: newLng };
    polygonCoords.push(finalCoord);
  }

  // Construct the polygon and add to the map:
  myPolygon = new google.maps.Polygon({
    paths: polygonCoords,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });
  myPolygon.setMap(map);
}
    </script>
  </head>
  <body>
    <div id='map'></div>
    <div id='panel'>
      Polygon to draw: <br>
      <textarea id='txt-coords' rows='10' cols='40' wrap='off'>28,86.1
28,88.5
26,88.5
26,86.1</textarea>
      <input id='btn-update' type='button' value='Update Map' onclick='updatePoygon()'>
      <br><br>
      Current marker:
      <input id='txt-marker-coord' type='text' value='click_on_map'>
    </div>
    <script> initMap(); </script>
  </body>
</html>

<!-- ACKNOWLEDGEMENTS:
Based on code from:
https://developers.google.com/maps/documentation/javascript/examples/polygon-simple
And some other fun code to see:
https://developers.google.com/maps/documentation/javascript/examples/drawing-tools !-->


Links