Skip to content Skip to sidebar Skip to footer

Convert Google Maps Polyline To Html Canvas Line

I need to show a google maps polyline into a html canvas. How I can convert the coordinates like this: lat:25.5643498,lng:45.34492432 to canvas coordinates like this? x:230,y:445

Solution 1:

Use the MapCanvasProjection method .fromLatLngToContainerPixel

proof of concept fiddle

code snippet:

var geocoder;
var map;
var overlay;
var shapes = [];


functioninitialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  overlay = new google.maps.OverlayView();
  overlay.draw = function() {};
  overlay.setMap(map);
  var drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.MARKER,
    drawingControl: true,
    drawingControlOptions: {
      position: google.maps.ControlPosition.TOP_CENTER,
      drawingModes: [
        google.maps.drawing.OverlayType.POLYLINE
      ]
    }
  });
  google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
    if (event.type == google.maps.drawing.OverlayType.POLYLINE) {
      if (drawingManager.getDrawingMode()) {
        drawingManager.setDrawingMode(null);
      }
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      context.clearRect(0, 0, canvas.width, canvas.height);
      var polyline = event.overlay;
      shapes.push(polyline);
      context.beginPath();
      for (var i = 0; i < polyline.getPath().getLength(); i++) {
        var point = overlay.getProjection().fromLatLngToContainerPixel(polyline.getPath().getAt(i));
        if (i == 0) {
          context.moveTo(point.x, point.y);
        } else {
          context.lineTo(point.x, point.y);
        }
      }
      context.stroke();
    }
  });
  drawingManager.setMap(map);
  google.maps.event.addListener(drawingManager, "drawingmode_changed", function() {
    if (drawingManager.getDrawingMode() != null) {
      for (var i = 0; i < shapes.length; i++) {
        shapes[i].setMap(null);
      }
      shapes = [];
    }
  });
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
{
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
#map_canvas {
  height: 400px;
  width: 500px;
}
<scriptsrc="https://maps.googleapis.com/maps/api/js?libraries=drawing&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script><canvasid="myCanvas"width="500"height="400"></canvas><divid="map_canvas"></div>

Post a Comment for "Convert Google Maps Polyline To Html Canvas Line"