Search code examples
javascriptgoogle-mapsshapesgoogle-polyline

Draw triangle based on latitude and longitude in google map


I need to create a triangle poly line in google map. But i do have only one latitude and longitude. Hence i just created the random value to create a shape in google map. But sometimes shapes are getting too much of difference. How to draw the triangle shape by one latitude and longitude. I just took reference from this link

Here is my code i used to draw the triangle shape in google map.

var geocoder = new google.maps.Geocoder();
var address = document.getElementById('valtxtaddres').value;
console.log("Address is:"+address);
if(address!=''){
geocoder.geocode( { 'address': address}, function(results, status) {

      if (status == google.maps.GeocoderStatus.OK) {
        var latitude = results[0].geometry.location.lat().toString();
        var longitude = results[0].geometry.location.lng().toString();
       // alert(latitude);
       console.log("Lng is:"+longitude);
        console.log("Math value:"+(Math.floor(Math.random()*90000) + 10000));
        var triangle2Lat = latitude.slice(0, latitude.length-5)+(Math.floor(Math.random()*90000) + 10000);
        var triangle2Lng = longitude.slice(0, longitude.length-11)+(Math.floor(Math.random()*90000) + 10000);
        var triangle3Lat = latitude.slice(0, latitude.length-5)+(Math.floor(Math.random()*90000) + 10000);
        var triangle3Lng = longitude.slice(0, longitude.length-11)+(Math.floor(Math.random()*90000) + 10000);
         console.log("triangle2Lat is:"+triangle2Lat);
        console.log("triangle2Lng is:"+triangle2Lng);
        console.log("triangle3Lat is:"+triangle3Lat);
        console.log("triangle3Lng is:"+triangle3Lng); 
        var triangleCoords = [
            new google.maps.LatLng(latitude, longitude),
            new google.maps.LatLng(triangle2Lat, triangle2Lng),
            new google.maps.LatLng(triangle3Lat, triangle3Lng)
          ];
myPolygon = new google.maps.Polygon({
    paths: triangleCoords,
    draggable: true, // turn off if it gets annoying
    editable: true,
    strokeColor: '#FF0000',
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: '#FF0000',
    fillOpacity: 0.35
  });

  myPolygon.setMap(gmap);
      } 
    }); 
}

Solution

  • You can use the spherical geometry library to draw a triangle with vertices 250 meters away from the geocoded point heading 0 degrees (north), 120 degrees (southeast) and -120 degrees (southwest).

    var geocoder = new google.maps.Geocoder();
    var address = document.getElementById('valtxtaddres').value;
    console.log("Address is:" + address);
    if (address != '') {
      geocoder.geocode({
        'address': address
      }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          var triangle1 = google.maps.geometry.spherical.computeOffset(results[0].geometry.location, 250, 0);
          var triangle2 = google.maps.geometry.spherical.computeOffset(results[0].geometry.location, 250, 120);
          var triangle3 = google.maps.geometry.spherical.computeOffset(results[0].geometry.location, 250, -120);
          var triangleCoords = [triangle1, triangle2, triangle3];
          myPolygon = new google.maps.Polygon({
            path: triangleCoords,
            strokeColor: '#FF0000',
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: '#FF0000',
            fillOpacity: 0.35
          });
          myPolygon.setMap(gmap);
        }
      });
    }
    

    proof of concept fiddle

    screenshot of resulting map

    code snippet:

    function initialize() {
      var gmap = new google.maps.Map(
        document.getElementById("map_canvas"), {
          center: new google.maps.LatLng(37.4419, -122.1419),
          zoom: 16,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
      var geocoder = new google.maps.Geocoder();
      var address = document.getElementById('valtxtaddres').value;
      console.log("Address is:" + address);
      if (address != '') {
        geocoder.geocode({
          'address': address
        }, function(results, status) {
    
          if (status == google.maps.GeocoderStatus.OK) {
            var mark = new google.maps.Marker({
              position: results[0].geometry.location,
              map: gmap,
              title: "C",
              icon: {
                url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
                size: new google.maps.Size(7, 7),
                anchor: new google.maps.Point(3.5, 3.5)
              }
            });
            var triangle1 = google.maps.geometry.spherical.computeOffset(results[0].geometry.location, 250, 0);
            var triangle2 = google.maps.geometry.spherical.computeOffset(results[0].geometry.location, 250, 120);
            var triangle3 = google.maps.geometry.spherical.computeOffset(results[0].geometry.location, 250, -120);
            console.log("triangle1 is:" + triangle1.toUrlValue(6));
            console.log("triangle2 is:" + triangle2.toUrlValue(6));
            console.log("triangle3 is:" + triangle3.toUrlValue(6));
            var triangleCoords = [triangle1, triangle2, triangle3];
            myPolygon = new google.maps.Polygon({
              path: triangleCoords,
              // draggable: true, // turn off if it gets annoying
              // editable: true,
              strokeColor: '#FF0000',
              strokeOpacity: 0.8,
              strokeWeight: 2,
              fillColor: '#FF0000',
              fillOpacity: 0.35
            });
    
            myPolygon.setMap(gmap);
          }
        });
      }
    }
    google.maps.event.addDomListener(window, "load", initialize);
    html,
    body {
      height: 100%;
      width: 100%;
      margin: 0px;
      padding: 0px
    }
    
    #map_canvas {
      height: 90%;
      width: 100%;
    }
    <script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
    <input id="valtxtaddres" value="Palo Alto, CA" />
    <div id="map_canvas"></div>