Async in custom google maps not work - javascript

I have a problem, when I using this code in custom maps from my server (below is example from google documentation, but my script is similar excluding the path to the map). Async loading not work for me:
<!DOCTYPE html>
<html>
<head>
<title>Image map types</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script>
var moonTypeOptions = {
getTileUrl: function(coord, zoom) {
var normalizedCoord = getNormalizedCoord(coord, zoom);
if (!normalizedCoord) {
return null;
}
var bound = Math.pow(2, zoom);
return 'http://mw1.google.com/mw-planetary/lunar/lunarmaps_v1/clem_bw' +
'/' + zoom + '/' + normalizedCoord.x + '/' +
(bound - normalizedCoord.y - 1) + '.jpg';
},
tileSize: new google.maps.Size(256, 256),
maxZoom: 9,
minZoom: 0,
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');
}
// 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 = 1 << 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
};
}
google.maps.event.addDomListener(window, 'load', initialize);
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://maps.googleapis.com/maps/api/js?sensor=false&' +
'callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
My site is blank and console show me:
Uncaught ReferenceError: google is not defined
But when I using this code:
<!DOCTYPE html>
<html>
<head>
<title>Image map types</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script>
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://maps.googleapis.com/maps/api/js?sensor=false&' +
'callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
var moonTypeOptions = {
getTileUrl: function(coord, zoom) {
var normalizedCoord = getNormalizedCoord(coord, zoom);
if (!normalizedCoord) {
return null;
}
var bound = Math.pow(2, zoom);
return 'http://mw1.google.com/mw-planetary/lunar/lunarmaps_v1/clem_bw' +
'/' + zoom + '/' + normalizedCoord.x + '/' +
(bound - normalizedCoord.y - 1) + '.jpg';
},
tileSize: new google.maps.Size(256, 256),
maxZoom: 9,
minZoom: 0,
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');
}
// 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 = 1 << 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
};
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
Google maps are loaded on the page, but still shows me:
Uncaught ReferenceError: google is not defined
What could be the reason?

Any occurence of google in global scope(outside of a function) will force this error. The first time you may access google is in initialize.

Related

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);
});

Google Maps Javascript API with an OpenWeatherMap Tile Layer Overlay

How can I overlay an XYZ tile set (something like this) on Google Maps API 3? I want to overlay weather data (cloud cover...etc). Feel free to use my OpenWeatherMaps URL to test it out:
http://maps.owm.io:8091/56ce0fcd4376d3010038aaa8/{z}/{x}/{y}?hash=5
I have spent multiple days trying to figure out this seemingly simple feature.
If someone can provide a working example I would be in your debt. Feel free to check out my GitHub Gist implementation using OL3 and OSM of this weather data overlay. I'd also love to know if this is not easily achievable/requires hacks.
Thank you!
Update: Thanks to #wf9a5m75's answer, I was able to put together this jsFiddle with the solution to my problem: https://jsfiddle.net/601oqwq2/4/
ImageMapType is for your purpose.
Read here: https://developers.google.com/maps/documentation/javascript/maptypes#ImageMapTypes
var myMapType = new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
return "http://maps.owm.io:8091/56ce0fcd4376d3010038aaa8/" +
zoom + "/" + coord.x + "/" + coord.y + "?hash=5";
},
tileSize: new google.maps.Size(256, 256),
maxZoom: 9,
minZoom: 0,
name: 'mymaptype'
});
map.mapTypes.set('mymaptype', myMapType);
map.setMapTypeId('mymaptype');
[update] Overlay the imageMapType above the current mapType
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
var myMapType = new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
return "http://maps.owm.io:8091/56ce0fcd4376d3010038aaa8/" +
zoom + "/" + coord.x + "/" + coord.y + "?hash=5";
},
tileSize: new google.maps.Size(256, 256),
maxZoom: 9,
minZoom: 0,
name: 'mymaptype'
});
map.overlayMapTypes.insertAt(0, myMapType);
Improving on wf9a5m75's answer.
The overlay image tiles don't cover the underlying map when zoomed out. We can make use of a normalization function (as mentioned in the link here) to ensure they cover the whole area.
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<body>
<div id="map"></div>
<script>
var map;
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 19.0356826,
lng: 72.9112641
},
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
});
var myMapType = new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
var normalizedCoord = getNormalizedCoord(coord, zoom);
if (!normalizedCoord) {
return null;
}
var bound = Math.pow(2, zoom);
return "http://maps.owm.io:8091/56ce0fcd4376d3010038aaa8/" +
zoom + "/" + normalizedCoord.x + "/" + (bound - normalizedCoord.y - 1) + "?hash=5";
},
tileSize: new google.maps.Size(256, 256),
maxZoom: 8,
minZoom: 0,
name: 'mymaptype'
});
// 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 = 1 << 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
};
}
map.overlayMapTypes.insertAt(0, myMapType);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
</body>

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/

Maximum call stack size exceeded / Too much recursion on Google maps API custom map type with allowed bounds

I'm trying to create a page using an custom map type image map as a background. I needed to restrict the panning on the image, so that it's not possible to pan past the image, but when panning the map left / right (along the x / longitude axis), the map disappears and I'm getting a "maximum stack size exceeded" (Chrome) or "too much recursion" (Firefox) error.
It turns out I'm not the only one having this issue, but in most of the cases, people had trouble with the decimal signs in the coordinates (, instead of .), but that is not my case since I don't use decimals.
I think this might be my case, but not sure how to go about the undefined latitude. (Mostly because I am quite new to JavaScript in general.)
This is all the code I'm using for the map:
function init() {
var map;
var repeatOnAxisX = false;
var blankTile = "img/map/empty.png";
var min_zoom = 4,
max_zoom = 5;
function getNormalizedCoord(coord, zoom) {
if(!repeatOnAxisX) return coord;
var totalTiles = 1 << (zoom - min_zoom),
y = coord.y,
x = coord.x;
var originX = 1 << (zoom - 1),
originY = 1 << (zoom - 1);
if(y < originX || y >= originX + totalTiles || x < originX || x >= originX + totalTiles) {
return null;
}
x -= originX;
y -= originY;
return {
x : x,
y : y
};
}
var customMapType = new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
var normalizedCoord = getNormalizedCoord(coord, zoom);
if(normalizedCoord) {
return "img/map/" + zoom + "/" + normalizedCoord.x + "/" + normalizedCoord.y + ".png";
} else {
return blankTile;
}
},
tileSize: new google.maps.Size(256, 256),
maxZoom: max_zoom,
minZoom: min_zoom,
name: "My Image Map"
});
var mapDiv = document.getElementById("map-canvas"),
myCenter = new google.maps.LatLng(-1, -1),
myOptions = {
zoom: 5,
center: myCenter,
streetViewControl: false,
mapTypeControl: false,
mapTypeControlOptions: {
mapTypeIds: ["custom"]
}
};
map = new google.maps.Map(mapDiv, myOptions);
map.mapTypes.set("custom", customMapType);
map.setMapTypeId("custom");
// Setting up the panning restriction
var allowedBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-67, -74),
new google.maps.LatLng(67, 74)
);
var boundLimits = {
maxLat: allowedBounds.getNorthEast().lat(),
maxLng: allowedBounds.getNorthEast().lng(),
minLat: allowedBounds.getSouthWest().lat(),
minLng: allowedBounds.getSouthWest().lng()
};
var lastValidCenter = map.getCenter();
var newLat, newLng;
google.maps.event.addListener(map, "center_changed", function() {
center = map.getCenter();
if(allowedBounds.contains(center)) {
// still within valid bounds, so save last valid position
lastValidCenter = map.getCenter();
return;
}
newLat = lastValidCenter.lat();
newLng = lastValidCenter.lng();
if(center.lng() > boundLimits.minLng && center.lng() < boundLimits.maxLng) {
newLng = center.lng();
}
if(center.lat() > boundLimits.minLat && center.lat() < boundLimits.maxLat) {
newLat = center.lat;
}
map.panTo(new google.maps.LatLng(newLat, newLng));
});
}
google.maps.event.addDomListener(window, "load", init);
(I'm using this solution to restrict the panning.)
EDIT: Here is a JSFiddle of the problem.
Any ideas / help is really appreciated! Than you!
In your center_changed listener where you check if your newLat and newLng are out of bounds, you assign to newLng the return value (number) of center.lng(), but to newLat you assign the function center.lat:
if(center.lng() > boundLimits.minLng && center.lng() < boundLimits.maxLng) {
newLng = center.lng();
}
if(center.lat() > boundLimits.minLat && center.lat() < boundLimits.maxLat) {
newLat = center.lat;
}
Obviously, you need to call center.lat:
newLat = center.lat();

Categories

Resources