Search code examples
javascriptgoogle-mapsgoogle-maps-api-2

Google Map API - display the longitudes and latitudes for multiple shapes in a textbox


I'm very new to JavaScript so your help would be much appreciated.

I'm working with this example of Google Map - http://gmaps-samples.googlecode.com/svn/trunk/poly/mymapstoolbar.html

This works perfect but what i would like to do is to display the latlongs for any shapes created (currently it only displays the latlong for the marker).

Instead of displaying the Line and Shape km info I would like to display the latlongs in a textbox as soon as the polygon/shape/line is created.

I tried editing the JavaScript and also checked the Google Documentation but getting errors on the page.

Thank you!!!

EDIT

CODE AFTER MAKING THE BELOW CHANGES

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- saved from url=(0069)http://gmaps-samples.googlecode.com/svn/trunk/poly/mymapstoolbar.html -->
<!--
 Copyright 2008 Google Inc. 
 Licensed under the Apache License, Version 2.0: 
 http://www.apache.org/licenses/LICENSE-2.0 
 --><HTML 
xmlns="http://www.w3.org/1999/xhtml"><HEAD><TITLE>Google Maps JavaScript API Example: Editable Polylines</TITLE>
<META content="text/html; charset=utf-8" http-equiv=content-type>
<SCRIPT type=text/javascript 
src="Google%20Maps%20JavaScript%20API%20Example%20Editable%20Polylines_files/maps"></SCRIPT>

<STYLE type=text/css>BODY {
    FONT-FAMILY: Arial, sans serif; FONT-SIZE: 11px
}
#hand_b {
    BACKGROUND-IMAGE: url(http://google.com/mapfiles/ms/t/Bsu.png); WIDTH: 31px; HEIGHT: 31px
}
.selected#hand_b {
    BACKGROUND-IMAGE: url(http://google.com/mapfiles/ms/t/Bsd.png)
}
#placemark_b {
    BACKGROUND-IMAGE: url(http://google.com/mapfiles/ms/t/Bmu.png); WIDTH: 31px; HEIGHT: 31px
}
.selected#placemark_b {
    BACKGROUND-IMAGE: url(http://google.com/mapfiles/ms/t/Bmd.png)
}
#line_b {
    BACKGROUND-IMAGE: url(http://google.com/mapfiles/ms/t/Blu.png); WIDTH: 31px; HEIGHT: 31px
}
.selected#line_b {
    BACKGROUND-IMAGE: url(http://google.com/mapfiles/ms/t/Bld.png)
}
#shape_b {
    BACKGROUND-IMAGE: url(http://google.com/mapfiles/ms/t/Bpu.png); WIDTH: 31px; HEIGHT: 31px
}
.selected#shape_b {
    BACKGROUND-IMAGE: url(http://google.com/mapfiles/ms/t/Bpd.png)
}
</STYLE>

<SCRIPT type=text/javascript>
var COLORS = [["red", "#ff0000"], ["orange", "#ff8800"], ["green","#008000"],
              ["blue", "#000080"], ["purple", "#800080"]];
var options = {};
var lineCounter_ = 0;
var shapeCounter_ = 0;
var markerCounter_ = 0;
var colorIndex_ = 0;
var featureTable_;
var map;

function select(buttonId) {
  document.getElementById("hand_b").className="unselected";
  document.getElementById("shape_b").className="unselected";
  document.getElementById("line_b").className="unselected";
  document.getElementById("placemark_b").className="unselected";
  document.getElementById(buttonId).className="selected";
}

function stopEditing() {
  select("hand_b");
}

function getColor(named) {
  return COLORS[(colorIndex_++) % COLORS.length][named ? 0 : 1];
}

function getIcon(color) {
  var icon = new GIcon();
  icon.image = "http://google.com/mapfiles/ms/micons/" + color + ".png";
  icon.iconSize = new GSize(32, 32);
  icon.iconAnchor = new GPoint(15, 32);
  return icon;
}

function startShape() {
  select("shape_b");
  var color = getColor(false);
  var polygon = new GPolygon([], color, 2, 0.7, color, 0.2);
  startDrawing(polygon, "Shape " + (++shapeCounter_), function() {
    var cell = this;
    var area = polygon.getArea();
    cell.innerHTML = (Math.round(area / 10000) / 100) + "km<sup>2</sup>";
}, color);

//    $("#controls_left").text("");   
//    for(var m=0; m<polygon.length; m++) { 
//      $("#controls_left").append("<textarea class='latlong'>" + polygon[m].getPoint().lat().toFixed(6) + "</textarea>");
//      $("#controls_left").append("<textarea class='latlong'>" + polygon[m].getPoint().lng().toFixed(6) + "</textarea>");  

}

function startLine() {
  select("line_b");
  var color = getColor(false);
  var line = new GPolyline([], color);
  startDrawing(line, "Line " + (++lineCounter_), function() {
    var cell = this;
    var len = line.getLength();
    cell.innerHTML = (Math.round(len / 10) / 100) + "km";
  }, color);
}

function addFeatureEntry(name, color) {
  currentRow_ = document.createElement("tr");
  var colorCell = document.createElement("td");
  currentRow_.appendChild(colorCell);
  colorCell.style.backgroundColor = color;
  colorCell.style.width = "1em";
  var nameCell = document.createElement("td");
  currentRow_.appendChild(nameCell);
  nameCell.innerHTML = name;
  var descriptionCell = document.createElement("td");
  currentRow_.appendChild(descriptionCell);
  featureTable_.appendChild(currentRow_);
  return {desc: descriptionCell, color: colorCell};
}

function startDrawing(poly, name, onUpdate, color) {
    map.addOverlay(poly);
    poly.enableDrawing(options);
    poly.enableEditing({ onEvent: "mouseover" });
    poly.disableEditing({ onEvent: "mouseout" });
    function () {
        select("hand_b");
        var cells = addFeatureEntry(name, color);
        updateDrawing(poly, cells);
        GEvent.addListener(poly, "click", function (latlng, index) {
            if (typeof index == "number") {
                poly.deleteVertex(index);
            } else {
                var newColor = getColor(false);
                cells.color.style.backgroundColor = newColor
                poly.setStrokeStyle({ color: newColor, weight: 4 });
            }
        });
    }
}



function placeMarker() {
  select("placemark_b");
  var listener = GEvent.addListener(map, "click", function(overlay, latlng) {
    if (latlng) {
      select("hand_b");
      GEvent.removeListener(listener);
      var color = getColor(true);
      var marker = new GMarker(latlng, {icon: getIcon(color), draggable: true});
      map.addOverlay(marker);
      var cells = addFeatureEntry("Placemark " + (++markerCounter_), color);
      updateMarker(marker, cells);
      GEvent.addListener(marker, "dragend", function() {
        updateMarker(marker, cells);
      });
      GEvent.addListener(marker, "click", function() {
        updateMarker(marker, cells, true);
      });
    }
  });
}

function updateMarker(marker, cells, opt_changeColor) {
  if (opt_changeColor) {
    var color = getColor(true);
    marker.setImage(getIcon(color).image);
    cells.color.style.backgroundColor = color;
  }
  var latlng = marker.getPoint();
  cells.desc.innerHTML = "(" + Math.round(latlng.y * 100) / 100 + ", " +
  Math.round(latlng.x * 100) / 100 + ")";
}


function updateDrawing(poly, cells) {
    var text = "(";
    for (var i = 0; i < poly.getVertexCount(); i++) {
        if (i > 0)
            text = text + "; ";
        var latlng = poly.getVertex(i);
        text = text + Math.round(latlng.y * 100) / 100 + ", " + Math.round(latlng.x * 100) / 100;
    }
    cells.desc.innerHTML = text + ")";
}


function initialize() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    map.setCenter(new GLatLng(37.4419, -122.1419), 13);
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    map.clearOverlays();
    featureTable_ = document.getElementById("featuretbody");
    select("hand_b");
  }
}

    </SCRIPT>

<META name=GENERATOR content="MSHTML 8.00.6001.19154"></HEAD>
<BODY onunload=GUnload onload=initialize()>
<TABLE>
  <TBODY>
  <TR style="VERTICAL-ALIGN: top">
    <TD style="WIDTH: 15em">
      <TABLE>
        <TBODY>
        <TR>
          <TD>
            <DIV id=hand_b onclick=stopEditing()>Move</DIV></TD>
          <TD>
            <DIV id=placemark_b onclick=placeMarker()>Marker</DIV></TD>
          <TD>
            <DIV id=line_b onclick=startLine()>Line</DIV></TD>
          <TD>
            <DIV id=shape_b 
      onclick=startShape()>Polygon</DIV></TD></TR></TBODY></TABLE><INPUT 
      id=featuredetails type=hidden rows="2"> </INPUT>
      <P>To draw on the map, click on one of the buttons and then click on the 
      map. Double-click to stop drawing a line or shape. Click on an element to 
      change color. To edit a line or shape, mouse over it and drag the points. 
      Click on a point to delete it. </P>
      <TABLE id=featuretable>
        <TBODY id=featuretbody></TBODY></TABLE></TD>
    <TD><!-- The frame used to measure the screen size -->
      <DIV id=frame></DIV>
      <DIV style="WIDTH: 600px; HEIGHT: 600px" 
id=map></DIV></TD></TR></TBODY></TABLE>

    <DIV id=controls_left </DIV>
    </BODY></HTML>

Solution

  • There are several ways to do it. The important thing here is to get the coordinates of polyline/polygon vertices. To do that use getVertexCount() and getVertex(index:Number) functions of GPolyline/GPolygon objects.

    Now you can take inspiration from updateMarker() function and create:

    function updateDrawing(poly, cells) {
       var text = "(";
       for(var i=0; i<poly.getVertexCount(); i++) {
          if(i > 0)
             text = text + "; ";
          var latlng = poly.getVertex(i);
          text = text + Math.round(latlng.y * 100) / 100 + ", " + Math.round(latlng.x * 100) / 100;
       }
       cells.desc.innerHTML = text + ")";
    }
    

    And change the endline event listener in startDrawing() function:

    function() {
       select("hand_b");
       var cells = addFeatureEntry(name, color);
       updateDrawing(poly, cells);
       GEvent.addListener(poly, "click", function(latlng, index) {
          if (typeof index == "number") {
             poly.deleteVertex(index);
          } else {
             var newColor = getColor(false);
             cells.color.style.backgroundColor = newColor
             poly.setStrokeStyle({color: newColor, weight: 4});
          }
       });
    }
    

    The lineupdated event listener is removed to prevent the text to be changed back to area/length.