1
我需要將谷歌地圖折線線顯示到HTML畫布中。我如何可以這樣轉換座標:將谷歌地圖折線轉換爲HTML畫布線
lat:25.5643498,lng:45.34492432
到canvas的座標是這樣的?
x:230,y:445
我試圖「規模」下,從谷歌,但沒有成功的座標。
我需要將谷歌地圖折線線顯示到HTML畫布中。我如何可以這樣轉換座標:將谷歌地圖折線轉換爲HTML畫布線
lat:25.5643498,lng:45.34492432
到canvas的座標是這樣的?
x:230,y:445
我試圖「規模」下,從谷歌,但沒有成功的座標。
使用MapCanvasProjection方法.fromLatLngToContainerPixel
代碼片斷:
var geocoder;
var map;
var overlay;
var shapes = [];
function initialize() {
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;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=drawing"></script>
<canvas id="myCanvas" width="500" height="400"></canvas>
<div id="map_canvas"></div>
謝謝。它完美的工作! – cristyan120
https://developers.google.com/maps/documentation/javascript /參考#MapCanvasProjecti – geocodezip
[如何縮放HTML5畫布以顯示Google地圖座標](http://stackoverflow.com/questions/27892300/how-to-scale-html5-canvas-to-show-google-maps-coordinates) – geocodezip