How to scale html5 canvas to show google maps coordinates - javascript

I have HTML5 canvas:
<canvas id="myCanvas" width="500" height="400"
style="border:1px solid #000000; background:#ccc;">
</canvas>
and here is easy to draw lines but line must be (x->max 500, y->max400) and thats ok.
But I how I can scale this canvas to show coordinates (latitude, longitude) - coordinates is high precision decimal values:
{"lat":"52.67554942424349","lng":"8.372654914855957"},{"lat":"52.67528921580262","lng":"8.373513221740723"},{"lat":"52.6759657545252","lng":"8.374114036560059"},{"lat":"52.682574466310314","lng":"8.37256908416748"},{"lat":"52.68356308524067","lng":"8.373942375183105"},{"lat":"52.68293869694087","lng":"8.375487327575684"},{"lat":"52.67685044320001","lng":"8.376259803771973"},{"lat":"52.6756535071859","lng":"8.379607200622559"},{"lat":"52.676017795531436","lng":"8.382096290588379"},{"lat":"52.68101344348877","lng":"8.380722999572754"},{"lat":"52.68351105322329","lng":"8.383641242980957"},
When I draw it on google map then looks like this:
IMAGE URL: http://i.stack.imgur.com/haTkH.png
How I can transform my decimal values from coordinates to show this coordinates from above on html5 canvas like on google map? Is there any way? I was spend 3 days to try to find solution for this probem? How that work?
thanks and sorry for my english

If you want to draw a lines in google maps, rather than using HTML 5, May be you can considering it using google maps api to draw a line.
if you want more info about how to using it. please read here.
And, if you want more detail about the API References, please read it here...
May be you should try this code snippet below, how to use this services from google maps api.
function initialize() {
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(-6.1839906,106.82296),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var flightPlanCoordinates = [
new google.maps.LatLng(-6.175392,106.827153),
new google.maps.LatLng(-6.1827,106.82296),
new google.maps.LatLng(-6.1839906,106.82296),
new google.maps.LatLng(-6.1860599,106.8217262)];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 3
});
flightPath.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<div id="map-canvas" style="height:400px; width:400px"></div>
May be you can precise the line for what you need to...

Related

Google Maps Marker in the wrong position

I am struggling to understand this.
My code is below along with a link to a test page showing the map
with marker in the wrong place.
I have set the lat and lng consistent with
https://www.google.co.uk/maps/place/Dakota+Hotel+Eurocentral/#55.8353173,-3.9854019,17z/data=!3m1!4b1!4m5!3m4!1s0x4888441f8bb5be07:0x6444cfc231481afe!8m2!3d55.8353173!4d-3.9832132
As you can see from the link they are 55.8353173 and -3.9854019
However when I include them in my code below - the marker appears in the wrong place.
See http://craigfagan.com/queenslie/testmap.html
My code is below.
Any help would be greatly appreciate on this - Scratching my head wondering what I am doing wrong?
Thanks in advance for any advice..
<div id="map"></div>
<script type="text/javascript">
function initMap() {
var mapOptions = {
zoom: 17,
scrollwheel: false,
center: new google.maps.LatLng(55.8353173,-3.9854019),
styles:
[{"featureType":"water","elementType":"geometry.fill","stylers":
[{"color":"#d3d3d3"}]},{"featureType":"transit","stylers":
[{"color":"#808080"},{"visibility":"off"}]},
{"featureType":"road.highway","elementType":"geometry.stroke",
"stylers":
[{"visibility":"on"},{"color":"#b3b3b3"}]},
{"featureType":"road.highway","elementType":"geometry.fill","stylers":
[{"color":"#ffffff"}]},
{"featureType":"road.local","elementType":"geometry.fill","stylers":
[{"visibility":"on"},{"color":"#ffffff"},{"weight":1.8}]},
{"featureType":"road.local","elementType":"geometry.stroke","stylers":
[{"color":"#d7d7d7"}]},
{"featureType":"poi","elementType":"geometry.fill","stylers":
[{"visibility":"on"},{"color":"#ebebeb"}]},
{"featureType":"administrative","elementType":"geometry","stylers":
[{"color":"#a7a7a7"}]},
{"featureType":"road.arterial","elementType":"geometry.fill","stylers":
[{"color":"#ffffff"}]},
{"featureType":"road.arterial","elementType":"geometry.fill","stylers":
[{"color":"#ffffff"}]},
{"featureType":"landscape","elementType":"geometry.fill","stylers":
[{"visibility":"on"},{"color":"#efefef"}]},
{"featureType":"road","elementType":"labels.text.fill","stylers":
[{"color":"#696969"}]},
{"featureType":"administrative","elementType":"labels.text.fill",
"stylers":
[{"visibility":"on"},{"color":"#737373"}]},
{"featureType":"poi","elementType":"labels.icon","stylers":
[{"visibility":"off"}]},
{"featureType":"poi","elementType":"labels","stylers":
[{"visibility":"off"}]},
{"featureType":"road.arterial","elementType":"geometry.stroke",
"stylers":
[{"color":"#d6d6d6"}]},
{"featureType":"road","elementType":"labels.icon","stylers":
[{"visibility":"off"}]},{},
{"featureType":"poi","elementType":"geometry.fill","stylers":
[{"color":"#dadada"}]}]
};
var mapElement = document.getElementById('map');
var map = new google.maps.Map(mapElement, mapOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(55.8353173,-3.9854019),
map: map,
title: 'Dakota'
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?
key=AIzaSyDJRdPso7qlkubRB66DafdHiBClCZoGGsI&callback=initMap" async
defer></script>
The coordinates in the link after the # sign are the center of the map, not the marker.
To get the center of the map in Google Maps, right click on the icon of the place, click "what's here", it will give you the coordinates (55.835326,-3.983235 for that example).
If I use the Places API (for "Dakota Hotel Eurocentral"), I get (55.8353173,-3.983213200000023), which is better.

highlight all routes (google maps) within a specific circle radius

I am using Google Maps Javascript API v3,
What i would like to do is to highlight all routes within a specific circle radius when choosing a point in the map (point coordinates and circle radius are input parameters).
I tried to use the Directions Services and i did manage to display all possible routes when origin and destination points and travelMode are specified and the provideRouteAlternatives option is set to true.
When setting the origin point to be the cirle center, is there way to set multiple destinations points (points on the circle perimeter), and then loop over availables routes and highlight them using Directions Service?
P.S.: i am not trying to draw a circle around a point but to highlight all roads within the circle radius.
Thanks.
This is a just-for-fun answer.
Not really an answer because it really feels like a dirty little hack, and also I am not sure to understand what exactly you are trying to highlight (is it all streets or the results of a Directions request — this is unclear from your question).
But basically, I added 2 maps. The first one is the base map and the other one is positioned on top of the first one, with a border radius, and styles applied.
I then synchronize both maps so that they both move relatively (when panning / zooming).
var myLatlng = new google.maps.LatLng(51.51, -0.12);
var styles = [{
"featureType": "road",
"elementType": "geometry.fill",
"stylers": [{
"color": "#ff3380"
}]
}];
var mapOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var roundedMapOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
scrollwheel: false,
styles: styles
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var roundedMap = new google.maps.Map(document.getElementById("map-rounded"), roundedMapOptions);
google.maps.event.addListener(map, 'drag', function () {
roundedMap.setCenter(map.getCenter());
});
google.maps.event.addListener(roundedMap, 'drag', function () {
map.setCenter(roundedMap.getCenter());
});
google.maps.event.addListener(map, 'idle', function () {
roundedMap.setCenter(map.getCenter());
});
google.maps.event.addListener(map, 'zoom_changed', function () {
roundedMap.setZoom(map.getZoom());
});
Note on the use of the idle event listener:
If you are dragging the map very quickly, sometimes the sync is kind of lost. So with the idle event listener, the maps are re-synced after a drag.
Note that I added the below CSS rule to hide the copyright on the rounded map:
#map-rounded .gm-style-cc {
display: none;
}
This is clearly against Google Maps TOS but since it is still there on the base map, I would think this is a fair or acceptable misuse of the API :)
JSFiddle demo

Outline and shade regions using the Google Maps JavaScript API

The Google Maps web application geocodes and outlines regional areas in a very nice fashion. Is this possible through the Google Maps JavaScript API? An example of the website:
https://maps.google.se/maps?q=sk%C3%A5ne&hl=sv&ie=UTF8&ll=57.1422,13.337402&spn=5.468408,16.907959&sll=39.290385,-76.612189&sspn=0.243658,0.528374&hnear=Sk%C3%A5ne+l%C3%A4n&t=m&z=7
This is the county of Skåne in Sweden. The Google Maps web application outlines it in red and shades it pink. I want to geocode and display regions like this with the Google Maps JavaScript API. How?
As far as I know the boundaries feature is not provided from the Google Map API v3 yet.
You need to know the boundaries in order to shape a polygon. The information which is returned by the Geocoder given the address in not enough to shape the boundaries. You may see the returned info here.
The Stockholm boundaries are: '17.73966,59.66395|17.75651,59.61827|17.81771,59.58645|17.84347,59.53069|17.78465,59.49340|17.78277,59.38916|17.83277,59.36500|17.93215,59.33652|18.00736,59.34496|18.09139,59.33444|18.05722,59.39139|18.12000,59.45388|18.19508,59.45012|18.16562,59.41083|18.32826,59.39795|18.28659,59.41228|18.25945,59.44638|18.31722,59.47361|18.37333,59.46694|18.66638,59.59138|18.69979,59.64409|18.74555,59.68916|18.84139,59.71249|18.98569,59.71666|19.03222,59.71999|19.07965,59.76743|18.93472,59.78361|18.86472,59.79804|18.96922,59.86561|19.06545,59.83250|19.07056,59.88972|19.00722,59.91277|18.92972,59.92472|18.89000,59.95805|18.81722,60.07548|18.77666,60.11084|18.71139,60.12806|18.63277,60.14500|18.50743,60.15265|18.44805,59.99249|18.37334,59.86500|18.29055,59.83527|18.15472,59.79556|18.08111,59.74014|17.96055,59.70472|17.89694,59.68916|17.73966,59.66395'
In conclusion the hard part is to find the boundaries for the cities you want to get drawn on your map. I'm not sure whether there is a free service which provides these boundaries. Check this Stackoverflow question to get more information about sites which provide boundaries.
In the below example when you click the Draw Stockholm button then the Stockholm is drawn on the map.
<html>
<head>
<head>
<title>Area calculator - Outline a property on a google map and find its area</title>
<title>Google Maps</title>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en">
</script>
<script type="text/javascript">
var map,
geocoder,
addressMarker,
mapCenter = new google.maps.LatLng(59.3426606750, 18.0736160278);
function initialize() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 7,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
geocoder = new google.maps.Geocoder();
}
function showAddress() {
var address = $('#to').val();
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function drawPolygon() {
// stockholm boundaries
var boundaries = '17.73966,59.66395|17.75651,59.61827|17.81771,59.58645|17.84347,59.53069|17.78465,59.49340|17.78277,59.38916|17.83277,59.36500|17.93215,59.33652|18.00736,59.34496|18.09139,59.33444|18.05722,59.39139|18.12000,59.45388|18.19508,59.45012|18.16562,59.41083|18.32826,59.39795|18.28659,59.41228|18.25945,59.44638|18.31722,59.47361|18.37333,59.46694|18.66638,59.59138|18.69979,59.64409|18.74555,59.68916|18.84139,59.71249|18.98569,59.71666|19.03222,59.71999|19.07965,59.76743|18.93472,59.78361|18.86472,59.79804|18.96922,59.86561|19.06545,59.83250|19.07056,59.88972|19.00722,59.91277|18.92972,59.92472|18.89000,59.95805|18.81722,60.07548|18.77666,60.11084|18.71139,60.12806|18.63277,60.14500|18.50743,60.15265|18.44805,59.99249|18.37334,59.86500|18.29055,59.83527|18.15472,59.79556|18.08111,59.74014|17.96055,59.70472|17.89694,59.68916|17.73966,59.66395';
var latLngArray = boundaries.split('|');
var points = [];
for (var i = 0; i < latLngArray.length; i++) {
pos = latLngArray[i].split(',');
points.push(new google.maps.LatLng(parseFloat(pos[1]), parseFloat(pos[0])));
}
var shape = new google.maps.Polygon({
paths: points,
strokeColor: '#ff0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#ff0000',
fillOpacity: 0.35
});
shape.setMap(map);
}
$(document).ready(function () {
initialize();
});
$(document).on('click', '.show-address', function (e) {
e.preventDefault();
showAddress();
});
$(document).on('click', '.draw-address', function (e) {
e.preventDefault();
drawPolygon();
});
</script>
</head>
<body>
<div id="basic-map">
<div id="map_canvas" style="height:150px;"></div>
<label for="to">Address</label>
<input type="text" id="to" value="Stockholm, Sweden" />
Show Address
Draw Stockholm
</div>
</body>
</html>
I hope this helps.

Google maps polygons

I want to draw multiple polygons in the same google map, what i need to do is to read latlngs from a listbox, they are in this way:
lat1,lng1,1
lat2,lng2,1
lat3,lng3,1
lat1,lng1,2
lat2,lng2,2
lat3,lng3,2
and depending on the value at the right(1 or 2) I will read the corresponding latlns and draw the polygon, actually i'm doing this, in my loop the polygons are painted but there´s a line connecting them, what can I do?,I mean, HOW CAN I DRAW POLYGONS WITHOUT THIS CONNECTING LINES?, thank you very much!!!
Here's my code:
<script type="text/javascript">
var bermudaTriangle=[];
var places = [];
var geoDataSplit;
function initialize() {
var mapDiv = document.getElementById('map_canvas');
var coords = document.getElementById("selPoly");
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(19.3162200000000, -99.2204930000000),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var latlng;
for (var i = 0; i < coords.options.length; i++)
{
var geoData = coords.options[i].text;
geoDataSplit = geoData.split(",");
var counter = geoDataSplit[2];
for (geoDataSplit[2] = 1; geoDataSplit[2] <= 2; geoDataSplit[2]++)
{
if (counter == geoDataSplit[2]) {
latlng = new google.maps.LatLng(parseFloat(geoDataSplit[0]), parseFloat(geoDataSplit[1]));
places.push(latlng);
bermudaTriangle = new google.maps.Polygon({
paths: places,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35
});
}
}
}
bermudaTriangle.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body style="font-family: Arial; border: 0 none;">
<form id="form1" runat="server">
<div>
<asp:ListBox ID="selPoly" runat="server"></asp:ListBox>
</div>
</form>
<div id="map_canvas" style="width: 1024px; height: 768px"></div>
</body>
Drawing polygons is drawing lines between points (the subsequent points you give, and possibly the first and last point on your list). When they enclose a space - you get a polygon and the space is filled with colour. The line is always there between the two subsequent points.
If you want separate polygons, you have to CREATE separate polygons (with new google.maps.Polygon). If all you get is a list of points, it is up to you to come up with or find an algorithm to detect that the space is already enclosed, and a new Polygon should be created.
By the way, with the algoritm as is now, the new google.maps.Polygon line could (and probably should) be pushed down, outside of the loop, in line preceding bermudaTriangle.setMap(map);
OH WAIT THERE ACTUALLY IS A SOLUTION. Or a half-solution at least. You can make the lines invisible (strokeOpacity: 0). The polygons will still be visible because of their filling, more or less like this:

How can some LatLng be used to place markers on a Google map, but not to draw a Polygon?

Roughly a week ago, I ran into a problem: on a custom google-powered map, my Polygons would not show up, while Markers for the same coordinates are totally ok. Despite my efforts with the Google Maps API, it seems I cannot find why.
Here is a link to a screenshot of the map. Purple arrows and numbers are my addition, they show:
The google.maps.Marker I could place at the edges of my "region".
The artifact generated by the google.maps.Polygon code. It is red as expected, but completely out of place and weirdly flat.
Here is the part of the code where Markers and Polygons are generated:
var regionData = tecMap.regions[r];
var regionMapMarkers = new google.maps.MVCArray();
for (c in regionData.coords) {
var point = projection.worldToMap(regionData.coords[c]);
debugRegionPoints.push(point);
var thisLatLng = projection.fromPointToLatLng(point);
debugRegionLatLngs.push(thisLatLng);
regionMapMarkers.push(thisLatLng);
}
regionMapMarkers.forEach(function(latLng, m){
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: '',
optimized: false
});
regionCorners.push(marker);
});
var paths = new google.maps.MVCArray();
paths.push(regionMapMarkers);
var region = new google.maps.Polygon({
fillColor: "#FF0000",
fillOpacity: 0.35,
map: map,
paths: paths,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2
});
regionPolys.push(region);
If you're wondering about the array of arrays, it's all on par with the Google Maps Javascript API.
If you want to have a look at the map and related scripts, you can find it here.
The code snippet is in Scripts/tectonicus.js, starting at line 659.
[Edit] Some debugging information:
It seems to be a rendering problem, not a "calculating" one.
From firebug console, in the map I linked, both
regionPolys[0].getPath().getArray();
and
for (i in regionCorners) {console.log(regionCorners[i].getPosition())};
will return
P { Na=0.20123958504464223, Oa=-22.5249097921875}
P { Na=-0.21702715474330336, Oa=-32.7277467}
P { Na=0.19466306397879407, Oa=-37.51230686484375}
P { Na=0.12889785332031245, Oa=-49.04594858671875}
If I'm right, it means they have the same coordinates, which is on par with the code.
[Edit2] New advances !
It seems that vectors have rendering problems when dealing with a custom projection, such as the one used to display this isometric Minecraft map. (Generated with Tectonicus)
After the last comments, I'm adding to the live code linked above two new debug Arrays,
debugRegionLatLngs and debugRegionPoints. Above code is updated so you can see what they contain.
[Edit3] Projection and coordinates
Crossing BicycleDude's research with mine, it's now almost certain that it's the custom projection that wrecks polygons. In fact, there is a possibly related bug in Google Maps' API.
This projection is used because Minecraft maps can be virtually infinite, and yet have to use a gmap, which wraps around after 360° longitude. Also related is the fact that ingame coordinates are rendered in an isometric way, while gmaps expects something more like the Mercator projection.
I tried tweaking the projection a bit, but had no interesting results so far.
Hmm, I looked at this further and I do see that sliver polygon. If you note your latitudes, they're extremely close to 0 degrees which means virtually a flat line near the equator. I validated this myself by pasting your coordinates into a brand new Google Maps sample and they do not appear to be spatially located with your markers, so, you need to review where the coordinate information is being manipulated, sorry, I know I didn't find your problem.
I modified Google Map's Bermuda triangle sample to use your coding style. i.e. I adopted your variables and followed the spirit of your code. This example display 3 markers and the draws a polygon for the Bermuda triangle.
<!DOCTYPE html>
<html>
<head>
<title>Bermuda Hack Triangle</title>
<meta name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<style type="text/css">
#map_canvas {
width: 500px;
height: 500px;
}
</style>
<script type="text/javascript" scr="https://github.com/douglascrockford/JSON-js/blob/master/json2.js"></script>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
function initialize() {
var myoptions = {
zoom: 4,
center: new google.maps.LatLng(25, -70),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(
document.getElementById('map_canvas'),
myoptions
);
// Create pseudo coordinates
var regionMapMarkers = new google.maps.MVCArray();
var p1 = new google.maps.LatLng(25, -80);
var p2 = new google.maps.LatLng(18, -66);
var p3 = new google.maps.LatLng(32, -64);
//p2.Qa += 360;
//p3.Qa -= 360;
regionMapMarkers.push(p1);
regionMapMarkers.push(p2);
regionMapMarkers.push(p3);
console.log(JSON.stringify(regionMapMarkers));
// Draw Markers
regionMapMarkers.forEach(function(latLng, m){
var marker = new google.maps.Marker(
{
position: latLng,
map: map,
title: '',
optimized: false
});
});
// Draw Polygon
var region = new google.maps.Polygon({
map: map,
paths: regionMapMarkers,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>
The sample works. If you were to run it you'll get the Bermuda triangle surrounded by markers. The question then lies, what can, in practice, impact your algorithm? So far, we've speculated that the Minecraft projection does something. I still believe that to be the case.
In order to validate that theory, I tried to wreck the Bermuda triangle sample. I tried adding and subtracting 360 degrees longitude to two points by uncommenting the following lines:
p2.Qa += 360;
p3.Qa -= 360;
What this does is it will still allow it to place the markers in the same location but the polygon fill goes absolutely spacko. I believe this is what is happening in your scenario.
What I then recommend for you to do is review coordinate system in your application. If you can choose new coordinates you can avoid such edge conditions from happening.
I noticed you're passing paths as an MVCArray which contains another MVCArray. Have you tried just passing a simple single-dimension array like in Google's example in the docs?
And do you need to call setMap() or is passing in the map property enough to make it render?
Below is Google's Polygon() code example... (from here)
function initialize() {
var myLatLng = new google.maps.LatLng(24.886436490787712, -70.2685546875);
var myOptions = {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var bermudaTriangle;
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var triangleCoords = [
new google.maps.LatLng(25.774252, -80.190262),
new google.maps.LatLng(18.466465, -66.118292),
new google.maps.LatLng(32.321384, -64.75737),
new google.maps.LatLng(25.774252, -80.190262)
];
// Construct the polygon
// Note that we don't specify an array or arrays, but instead just
// a simple array of LatLngs in the paths property
bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
}

Categories

Resources