How can I change speed animated object? [JavaScript and Google Maps] - javascript

I'm creating project "flight controller" in order to pass the subject in my university. I imported Google Maps and I wrote a animated airplane.
var lineCoordinates = [
new google.maps.LatLng(fromX, fromY),
new google.maps.LatLng(toX, toY)
];
var lineSymbol = {
path: //SVG samolotu///,
scale: 0.5,
strokeColor: 'black',
fillColor: 'black',
fillOpacity: 1
};
var line = new google.maps.Polyline({
path: lineCoordinates,
icons: [{
icon: lineSymbol,
offset: '100%'
}],
});
line.setMap(map);
var count = 0;
window.setInterval(function() {
count = (count + 1) % 200;
if(count ==199) stopCircle(line);
var icons = line.get('icons');
icons[0].offset = (count / 2) + '%';
line.set('icons', icons);
},20);
But this solution has one defect. All airplane flight the same time, it's not depends on track.I must do that all airplane will have the same speed (not travel time). But If I zoom on my map , the airplane will move faster;) Can somebody help me?

(sorry if I ignore most of your code)
Okay, let's say we move the icon 100 km every second.
The main thing about the solution is this line; it returns a position that is X distance away from a point, along a route:
var pos = google.maps.geometry.spherical.computeOffset(start, newOffset, google.maps.geometry.spherical.computeHeading(start, end));
Here is an example you can copy/paste as is. I hope you can use this to do make your project.
If you want diferent speed and interval, look at lines 21 & 22.
<!DOCTYPE html>
<html>
<head>
<title>Google Maps - animated Airline Routes</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map_canvas {
height: 400px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry"></script>
<script>
function initialize() {
var map = new google.maps.Map(document.getElementById("map_canvas"), {
zoom: 6,
center: new google.maps.LatLng(50.5, 4.5), // Over Belgium
mapTypeId: google.maps.MapTypeId.TERRAIN
});
// settings:
previewInterval = 1000;
previewSpeed = 100; // 100 km (on the map) / interval time
// these variables will control the moving icon
var flightPathCoordinates=[
[4.485600, 50.90098, 20.96801, 52.167250], // Brussels - Warshau
[4.485600, 50.90098, -0.454256, 51.470054] // Brussels - London
];
var flightPathObjects = [];
var timers = [];
var markers = [];
// now we draw flight paths. notice, the 2 blocks here below can be put in a for-loop
// first path (i = 0)
var path = flightPathCoordinates[0];
var distance = google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(path[1], path[0]), new google.maps.LatLng(path[3], path[2]));
flightPathObjects.push(drawPath(path[0], path[1], path[2], path[3])); // draw path
markers.push(drawIcon(0)); // set the icon
animateIcon(0, 0, distance);
// second path (i = 1)
path = flightPathCoordinates[1];
distance = google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(path[1], path[0]), new google.maps.LatLng(path[3], path[2]));
flightPathObjects.push(drawPath(path[0], path[1], path[2], path[3]));
markers.push(drawIcon(1));
animateIcon(1, 0, distance);
/**
* Draw a flight path
*/
function drawPath(fromX, fromY, toX, toY) {
var lineCoordinates = [
new google.maps.LatLng(fromY, fromX), // notice: X is along the longitude, Y is along the lattitude
new google.maps.LatLng(toY, toX)
];
var line = new google.maps.Polyline({
path: lineCoordinates,
geodesic: true,
strokeColor: '#00FF00',
strokeOpacity: 1.0,
strokeWeight: 2
});
line.setMap(map);
return line;
}
/**
* recursive function. animates the the icon.
*/
function animateIcon(i, offset, totalDistance) {
var newOffset = (offset + previewSpeed * 1000) % totalDistance; // notice, the "% totalDistance" makes the plane loop. You could also stop the function if the distance > totalDistance
var start = new google.maps.LatLng(flightPathCoordinates[i][1], flightPathCoordinates[i][0]);
var end = new google.maps.LatLng(flightPathCoordinates[i][3], flightPathCoordinates[i][2]);
var pos = google.maps.geometry.spherical.computeOffset(start, newOffset, google.maps.geometry.spherical.computeHeading(start, end));
markers[i].setPosition(pos);
timers[i] = setTimeout(function () { // we trigger this function again in 1 second
animateIcon(i, newOffset, totalDistance)
}, previewInterval
);
}
/**
* sets a marker on the map, at the start of the path
*/
function drawIcon(i) {
var start = new google.maps.LatLng(flightPathCoordinates[i][1], flightPathCoordinates[i][0]);
var marker = new google.maps.Marker({
position: start,
icon: 'https://cdn0.iconfinder.com/data/icons/opensourceicons/32/plane.png', // you have your own icon ...
map: map
});
return marker;
}
}
google.maps.event.addDomListener(window, 'load', initialize);
//
</script>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>

Related

Google Maps Api draw my polygon (rectangle) as parallelogram

I can't manage with drawing rectangle between two cities. I've searched everywhere on the Internet and can't find out why my polygon is drawn on Google Maps as parallelogram even so on 2d plane (not earth plane) this rectangle is drawn properly.
What I noticed is that the curvature sides of parallelogram depends on where cities are placed on map. If two cities are placed vis-a-vis then my function draw rectangle successfully. But If they are placed diagonally then my function draw parallelogram. The result should be rotated rectangle with height as distance between two cities and width as kilometers that user chooses.
Here is my function that should draw rectangle between two cities. As args we need to give position of first city ($x1 is lat, $y1 is lng), position of second city and as third arg a radius in kilometers ($l1) from center point of rectangle.
function getPolygon($x1,$y1,$x2,$y2,$l1){
var $l1 = $l1*0.010526; //approx kilometers
var $distanceV = [($x2 - $x1), ($y2 - $y1)];
var $vlen = Math.sqrt(Math.pow($distanceV[0], 2) +
Math.pow($distanceV[1],2));
if($vlen == 0)
return [[0,0],[0,0],[0,0],[0,0]];
var $l2 = $vlen;
var $normalized = [($distanceV[0] / $vlen), ($distanceV[1] / $vlen)];
var $rotated = [(-1 * $normalized[1]), ($normalized[0])];
var $p1 = [($x1 - $rotated[0] * $l1 / 2), ($y1 - $rotated[1] * $l1 / 2)];
var $p2 = [($p1[0] + $rotated[0] * $l1), ($p1[1] + $rotated[1] * $l1)];
var $p3 = [($p1[0] + $normalized[0] * $l2), ($p1[1] + $normalized[1] * $l2)];
var $p4 = [($p3[0] + $rotated[0] * $l1), ($p3[1] + $rotated[1] * $l1)];
var $points = [
{lat: $p1[0], lng: $p1[1]},
{lat: $p3[0], lng: $p3[1]},
{lat: $p4[0], lng: $p4[1]},
{lat: $p2[0], lng: $p2[1]},
{lat: $p1[0], lng: $p1[1]}
];
return $points;
}
Then I draw it on Google Maps like this:
new google.maps.Polygon({
paths: getPolygon(first_city_lat, first_city_lng, second_city_lat, second_city_lng, 30),
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.05
});
Here is an example should be rectangle between Birmingham and Oxford: JSFiddle
Additionally I'm sure that kilometers converter is not exact and it again depends how cities are placed.
The earth is curved. To get a polygon that appears rectangular on the curved sphere, you need to use calculations that take the projection of the map into account.
The Google Maps Javascript API v3 has a spherical geometry library that can be used to compute the desired points.
function getPolygon($x1,$y1,$x2,$y2,$l1){
var points = [];
var city1 = new google.maps.LatLng($x1, $y1);
var city2 = new google.maps.LatLng($x2, $y2);
var heading = google.maps.geometry.spherical.computeHeading(city1, city2);
points.push(google.maps.geometry.spherical.computeOffset(city1, $l1/2*1000, heading+90));
points.push(google.maps.geometry.spherical.computeOffset(city1, $l1/2*1000, heading-90));
points.push(google.maps.geometry.spherical.computeOffset(city2, $l1/2*1000, heading-90));
points.push(google.maps.geometry.spherical.computeOffset(city2, $l1/2*1000, heading+90));
points.push(points[0]);
return points;
}
proof of concept fiddle
code snippet:
var map;
google.maps.event.addDomListener(window, "load", function() {
var map = new google.maps.Map(document.getElementById("map_div"), {
center: new google.maps.LatLng(52.489471, -1.898575),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var trace = new google.maps.Polygon({
paths: getPolygon(52.489471, -1.898575, 51.752022, -1.257677, 30),
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.05,
map: map
});
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < trace.getPath().getLength(); i++) {
bounds.extend(trace.getPath().getAt(i));
}
map.fitBounds(bounds);
function getPolygon($x1, $y1, $x2, $y2, $l1) {
var points = [];
var city1 = new google.maps.LatLng($x1, $y1);
var city2 = new google.maps.LatLng($x2, $y2);
var heading = google.maps.geometry.spherical.computeHeading(city1, city2);
points.push(google.maps.geometry.spherical.computeOffset(city1, $l1 / 2 * 1000, heading + 90));
points.push(google.maps.geometry.spherical.computeOffset(city1, $l1 / 2 * 1000, heading - 90));
points.push(google.maps.geometry.spherical.computeOffset(city2, $l1 / 2 * 1000, heading - 90));
points.push(google.maps.geometry.spherical.computeOffset(city2, $l1 / 2 * 1000, heading + 90));
points.push(points[0]);
return points;
}
});
html,
body {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px;
}
#map_div {
height: 95%;
}
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map_div"></div>

Google Maps V3: Hexagon grid - Error with setWindow

I am making hexagon grid for my game based on Google Map v3 and got a problem.
After I click in one hexagon are showing differents values, not one the same as for marker inside of the all hexagon.
The right value is showing just in the left down corner of quarter hexagon.
The value of coord_slug is making based on coordinates lat, lng.
What I have to do hexagon and marker values being the same ?
In this way 55.3,14.8 for upper and 55.25,1485 for down hexagon.
I need those values in a game for downloading dates from database.
The part responsible for displaying the value:
function set_window(event) {
// Set Parameters
var lat = event.latLng.lat();
var lng = event.latLng.lng();
var coord_slug = (Math.round(lat * 20) / 20) + ',' + (Math.round(lng * 20) / 20);
alert(coord_slug);
}
The working part of the script here:
function round_down(n) {
if (n > 0) {
return Math.ceil(n / 0.05) * 0.05;
} else {
return 0;
}
}
var map;
var pointCount = 0;
var locations = [];
var gridWidth = 3660; // hex tile size in meters
var bounds;
var places = [
[55.3, 14.8],
[55.25, 14.85],
]
var SQRT3 = 1.73205080756887729352744634150587236;
$(document).ready(function(){
bounds = new google.maps.LatLngBounds();
map = new google.maps.Map(document.getElementById("map_canvas"), {center: {lat: 55.27, lng: 14.8}, zoom: 10});
// Adding a marker just so we can visualize where the actual data points are.
// In the end, we want to see the hex tile that contain them
places.forEach(function(place, p){
latlng = new google.maps.LatLng({lat: place[0], lng: place[1]});
marker = new google.maps.Marker({
position: latlng,
map: map})
marker.addListener('click', set_window);
// Fitting to bounds so the map is zoomed to the right place
bounds.extend(latlng);
});
// Now, we draw our hexagons! (or try to)
locations = makeBins(places);
locations.forEach(function(place, p){
drawHorizontalHexagon(map, place, gridWidth);
})
});
function drawHorizontalHexagon(map, position, radius){
var coordinates = [];
for(var angle= 0;angle < 360; angle+=60) {
coordinates.push(google.maps.geometry.spherical.computeOffset(position, radius, angle));
}
// Construct the polygon.
var polygon = new google.maps.Polygon({
paths: coordinates,
position: position,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
geodesic: true
});
polygon.setMap(map);
polygon.addListener('click', set_window);
}
// Below is my attempt at porting binner.py to Javascript.
// Source: https://github.com/coryfoo/hexbins/blob/master/hexbin/binner.py
function distance(x1, y1, x2, y2){
console.log(x1, y1, x2, y2);
result = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
console.log("Distance: ", result);
return
}
function nearestCenterPoint(value, scale){
div = value / (scale/2);
console.log("div", div);
mod = value % (scale/2);
console.log("mod", mod);
if(div % 2 == 1){
increment = 1;
} else{
increment = 0;
}
rounded = scale / 2 * (div + increment);
if(div % 2 === 0){
increment = 1;
} else{
increment = 0;
}
rounded_scaled = scale / 2 * (div + increment);
result = [rounded, rounded_scaled]
console.log("nearest centerpoint to", value, result);
return result;
}
function makeBins(data){
bins = [];
data.forEach(function(place, p){
x = place[0];
y = place[1];
console.log("Original location:", x, y);
px_nearest = nearestCenterPoint(x, gridWidth);
py_nearest = nearestCenterPoint(y, gridWidth * SQRT3);
z1 = distance(x, y, px_nearest[0], py_nearest[0]);
z2 = distance(x, y, px_nearest[1], py_nearest[1]);
if(z1 > z2){
bin = new google.maps.LatLng({lat: px_nearest[0], lng: py_nearest[0]});
console.log("Final location:", px_nearest[0], py_nearest[0]);
} else {
bin = new google.maps.LatLng({lat: px_nearest[1], lng: py_nearest[1]});
console.log("Final location:", px_nearest[1], py_nearest[1]);
}
bins.push(bin);
})
return bins;
}
function set_window(event) {
// Set Parameters
var lat = event.latLng.lat();
var lng = event.latLng.lng();
var coord_slug = (Math.round(lat * 20) / 20) + ',' + (Math.round(lng * 20) / 20);
alert(coord_slug);
}
<html>
<head>
<script data-require="jquery#*" data-semver="2.2.0" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script data-require="bootstrap#*" data-semver="3.3.6" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link data-require="bootstrap-css#3.3.6" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
</head>
<body>
<div id="map_canvas" style="width:100%; height:80vh;">
</div>
</body>
</html>
Additional link:
The working part of the script in Plunger
You are setting a position attribute to your Polygons, which seems to be what you want to display...
So you can replace the following
polygon.addListener('click', set_window);
By this:
polygon.addListener('click', function() {
var polyPosition = this.position.lat() + ', ' + this.position.lng();
alert(polyPosition);
});

Labeling GoogleMaps Lat/Lng intersection

I create a map with latitude and longitude lines drawn every 1/4 min. The resulting boxes are called Quarter Minutes. I need to label each Quarter Minute box. The label should be the lat/lon of the SW corner inside the box. Since I draw all the latitude lines within the viewing area first, and then all the longitude lines, I cannot figure out how to find the intersect point. It would seem, that I would draw one(1) latitude line, and then one(1) longitude line and then label the intersect. I figure I can just use an info box at each point.
I do not know how to do this in JavaScript. Maybe it is not necessary to trap the intersection at the point of creation but that is the only way I would think it would happen.
The syntax for a QtrMin is
3040A8415A = intersect at 30 40' by 84 15'
3040A8415B = intersect at 30 40' by 84 15' 15"
3040A8415C = intersect at 30 40' by 84 15' 30"
3040A8415D = intersect at 30 40' by 84 15' 45"
or DDMM and A-> D to designate each quarter of minute.
Longitude and latitude are treated the same.
What I have is:
<html>
<head>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry&sensor=false"></script>
<title>Find your Qtr minute locator</title>
</head>
<body style="height:100%;margin:0">
<!-- Declare the div, make it take up the full document body -->
<div id="map-canvas" style="width: 100%; height: 100%;"></div>
<script type="text/javascript">
var map;
var llOffset = 0.0666666666666667;
var drawGridBox = false;
var gridOverBox = new google.maps.Polyline({
path: [],
geodesic: true,
strokeColor: '',
strokeOpacity: 0,
strokeWeight: 0
});
var gridline;
var polylinesquare;
var latPolylines = [];
var lngPolylines = [];
var smLngPolylines = [];
var lngLabels = [];
var lngMapLabel;
var bounds = new google.maps.LatLngBounds();
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(34.00, -84.00),
zoom: 10,
streetViewControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scaleControl: true
});
DrawGridOn();
google.maps.event.addListener(map, 'idle', function () {
createGridLines(map.getBounds());
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function DrawGridOn() {
drawGridBox = true;
}
function DrawGridOff() {
drawGridBox = false;
}
function createGridLines(bounds) {
for (var i = 0; i < latPolylines.length; i++) {
latPolylines[i].setMap(null);
}
latPolylines = [];
for (var i = 0; i < lngPolylines.length; i++) {
lngPolylines[i].setMap(null);
}
lngPolylines = [];
if (map.getZoom() < 10) return;
var north = bounds.getNorthEast().lat();
var east = bounds.getNorthEast().lng();
var south = bounds.getSouthWest().lat();
var west = bounds.getSouthWest().lng();
// define the size of the grid
var topLat = Math.ceil(north / llOffset) * llOffset;
var rightLong = Math.ceil(east / llOffset) * llOffset;
var bottomLat = Math.floor(south / llOffset) * llOffset;
var leftLong = Math.floor(west / llOffset) * llOffset;
for (var latitude = bottomLat; latitude <= topLat; latitude += llOffset) latPolylines.push(new google.maps.Polyline({
path: [
new google.maps.LatLng(latitude, leftLong), new google.maps.LatLng(latitude, rightLong)],
map: map,
geodesic: true,
strokeColor: '#0000FF',
strokeOpacity: 0.5,
strokeWeight: 1
}));
for (var longitude = leftLong; longitude <= rightLong; longitude += llOffset) lngPolylines.push(new google.maps.Polyline({
path: [
new google.maps.LatLng(topLat, longitude), new google.maps.LatLng(bottomLat, longitude)],
map: map,
geodesic: true,
strokeColor: '#0000FF',
strokeOpacity: 0.5,
strokeWeight: 1
}));
}
</script>
</body>
</html>
Maybe it is not necessary to trap the intersection at the point of creation but that is the only way I would think it would happen
You draw straight lines with either equal latitudes or longitudes, so you may assume that the intersection of 2 lines:
latLine a: ay1,ax1 ay1,ax2
lngLine b: by1,bx1 by2,bx1
...is ay1,bx1
When the lines have been created iterate over them and create the labels based on the latitudes/longitudes:
//put the next 4 lines to the top of createGridLines
for(var i=0;i<lngLabels.length;++i){
lngLabels[i].setMap(null);
}
lngLabels=[];
//put this at the end of createGridLines
for(var x=0;x<latPolylines.length;++x){
for(var y=0;y<lngPolylines.length-1;++y){
var latLng=new google.maps.LatLng(latPolylines[x].getPath().getAt(0).lat(),
lngPolylines[y].getPath().getAt(0).lng());
lngLabels.push(new google.maps.Marker({
map:map,
position:latLng,
icon:{ url:'https://chart.googleapis.com/chart?'
+'chst=d_bubble_text_small&chld=bb|'
+ latLng.toUrlValue()
+'|FFFFFF|000000',
anchor:new google.maps.Point(0,42)
}
}));
}
}

Horizontal repeating Google Maps Marker on ImageMapType

<!DOCTYPE html>
<html>
<head>
<title>Image map types</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
var moonTypeOptions = {
getTileUrl: function(coord, zoom) {
var bound = Math.pow(2, zoom);
return 'full-out' +
'/' + zoom + '/' + coord.x + '/' +
(bound - coord.y - 1) + '.png';
},
tileSize: new google.maps.Size(256, 256),
maxZoom: 6,
minZoom: 1,
radius: 1738000,
name: 'Moon'
};
var moonMapType = new google.maps.ImageMapType(moonTypeOptions);
function initialize() {
var myLatlng = new google.maps.LatLng(0, 0);
var mapOptions = {
center: myLatlng,
zoom: 1,
streetViewControl: false,
mapTypeControlOptions: {
mapTypeIds: ['moon']
}
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
map.mapTypes.set('moon', moonMapType);
map.setMapTypeId('moon');
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
I have above code to render a custom large 16834 * 16834 image of 19 mb which is broken into tiles using gdal2tiles and gdal_translate. In short, I have all the corresponding tiles.
The above code is working perfectly fine rendering image and different zoom levels. However, when I add marker, it is displayed multiple times at lower zoom level. I would like the marker not repeat itself horizontally.
Is there any way to avoid horizontal repeating markers? Currently, I'm using Leaflet.js which doesn't repeat marker horizontally as Google Maps library.
I want to use Google maps because of its stability and popularity.
I'm using Ubuntu 14.04 as OS.
set the optimized-option of the markers to false
For those who has still this problem, have a look at my solution.
1- Set the maps zoom to (2) and add marker positions (lat,long) i.e
var minZoomLevel = 2;
map.setZoom(minZoomLevel);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < result.length; i++){
var latlng = new google.maps.LatLng(result[i].Lat, result[i].Lng);
bounds.extend(latlng);
});
2- Attach a event listener on zoom changed i.e
google.maps.event.addListener(map, 'zoom_changed', function() {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
3- Attach a center changed listener (This done the trick) i.e
google.maps.event.addListener(map, 'center_changed', function()
{
checkBounds(bounds);
}
function checkBounds(allowedBounds) {
if(allowedBounds.contains(map.getCenter())) {
return;
}
var mapCenter = map.getCenter();
var X = mapCenter.lng();
var Y = mapCenter.lat();
var AmaxX = allowedBounds.getNorthEast().lng();
var AmaxY = allowedBounds.getNorthEast().lat();
var AminX = allowedBounds.getSouthWest().lng();
var AminY = allowedBounds.getSouthWest().lat();
if (X < AminX) {X = AminX;}
if (X > AmaxX) {X = AmaxX;}
if (Y < AminY) {Y = AminY;}
if (Y > AmaxY) {Y = AmaxY;}
map.setCenter(new google.maps.LatLng(Y,X));
}
Every time you change the center, it will check your points and restrict map to certain area . Setting zoom will show only one world tile, and check bound will restrict the horizontal scrolling, thats how your markers will show only one time in map, set zoom according to your condition that fits in !!

Google Maps v3 API Markers doesn't work and leave a blank page

I'm trying to make a custom map with markers.
I already got a custom map that work's but when i try to add a marker it results in a blank page.
i have no idea what im doing wrong because i did everything i should do, unless I missed something.
I used custom images that are public available
my correct code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1.0,user-scalable=no" />
<meta charset="utf-8" />
<title>Nexoness Nation - Google Maps</title>
<link rel="shortcut icon" href="https://maps.gstatic.com/favicon3.ico"/>
</head>
<body onload="initialize()">
<div id="map-canvas" style="width: 100%; height: 100%"></div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var customMapTypeOptions = {
getTileUrl: function(coord, zoom) {
var normalizedCoord = getNormalizedCoord(coord, zoom);
if (!normalizedCoord) {
return null;
}
var bound = Math.pow(2, zoom);
/*Edit this URL to where you upload your tiles...*/
return "http://nexonessnation.bugs3.com/tile_" + zoom + "_" + normalizedCoord.x + "-" + normalizedCoord.y + ".svg";
},
tileSize: new google.maps.Size(256, 256),
isPng: true,
maxZoom: 3,
minZoom: 0,
name: "Nexoness Nation"
};
var customMapType = new google.maps.ImageMapType(customMapTypeOptions);
// Normalizes the coords that tiles repeat across the x axis (horizontally)
// like the standard Google map tiles.
function getNormalizedCoord(coord, zoom) {
var y = coord.y;
var x = coord.x;
// tile range in one direction range is dependent on zoom level
// 0 = 1 tile, 1 = 2 tiles, 2 = 4 tiles, 3 = 8 tiles, etc
var tileRange = 8 << zoom;
// don't repeat across y-axis (vertically)
if (y < 0 || y >= tileRange) {
return null;
}
// repeat across x-axis
if (x < 0 || x >= tileRange) {
x = (x % tileRange + tileRange) % tileRange;
}
return {
x: x,
y: y
};
}
function initialize() {
var myLatlng = new google.maps.LatLng(0, 0);
var myOptions = {
zoom: 1,
center: myLatlng,
mapTypeControlOptions: {
mapTypeIds: ["Nexoness Nation"]
}
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map.mapTypes.set('Nexoness Nation', customMapType);
map.setMapTypeId('Nexoness Nation');
}
function addMarkers() {
var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
var lngSpan = northEast.lng() - southWest.lng();
var latSpan = northEast.lat() - southWest.lat();
for (var i = 0; i < 10; i++) {
var latLng = new google.maps.LatLng(southWest.lat() + latSpan * Math.random(),
southWest.lng() + lngSpan * Math.random());
var marker = new google.maps.Marker({
position: latLng,
map: map_canvas
});
}
}
</script>
</body>
</html>
Does anybody see what i'm doing wrong?
The ID of your div ("map-canvas") in <div id="map-canvas" style="width: 100%; height: 100%"></div> does not match the id you indicate in your script: map = new google.maps.Map(document.getElementById("**map_canvas**"), myOptions);
Also in the jsfiddle you provided, you need to select no wrap - <in body> instead of onLoad in the second dropdown on the left menu because you're calling your initialize() function in the onLoad of the body.
Update: indeed, I forgot about the markers. First the function addMarkers() wasn't called from initialize(). Also let's not forget to send the "map" as a parameter so we can use it in addMarkers.
Finally getBounds is available after the event bounds_changed is fired, we just need to add a listener on it to get the values.
Here is a jsfiddle that works:
http://jsfiddle.net/M2RD6/4/

Categories

Resources