Google Maps API not showing (fixed height / width does not solve) - javascript

Showing the map was working before but for some reason I can't really figure it stopped working.
Here is my html inclusion:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=THIS_KEY_IS_CORRECT">
</script>
And here is my html:
(with style tags)
#map { height: 500px; }
<div id="map" > </div>
And my javascript
setTimeout(() => {
console.log("Running init map");
var map_div = document.getElementById("map");
var map_handler = new google.maps.Map(map_div, map_options);
console.log(map_handler);
},2000);
Here is the console log of map_handler:
ug {__gm: Yf, W: undefined, mapTypes: Object, features: Object, overlayMapTypes: _.td…}
So map_handler is actually returning something.
As I said, this used to work. For some reason it does not anymore.
Any idea why?
Thank you very much.

While this isn't the primary source of your issue - please note that you can't rely on setTimeout to tell you when the google maps JS API has been loaded. Use a callback:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=THIS_KEY_IS_CORRECT&callback=myMapIsReady">
</script>
And then
<script>
var myMapIsReady = function() {
console.log("Running init map");
var map_div = document.getElementById("map");
var map_handler = new google.maps.Map(map_div, map_options);
console.log(map_handler);
};
</script>
Here's the question, why are you saying this isn't working? How is it not working? What do you see on your screen?
A hint might be what is map_options you haven't shown where it is defined and if you init a google map with no center latlng/zoom, you'll just see a grey block.

Related

get the context of a created canvas with JQuery

I'm trying to use this methods ( http://jsfiddle.net/erickzanardo/RHZL6/ ) to create a canvas with createElement and then draw on it, but since I'm using JQuery the canvas so created deosn't have a class function getContext("2d"), but it seems to work on the last jsfiddle.
My code is as follow :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
var map_rendered = document.createElement("map");
map_rendered.heigt = 100 ; map_rendered.width = 100 ;
var map_rendered_ctx = map_rendered.getContext("2d");
the error I get is :
TypeError: map_rendered.getContext is not a function
Do you have a way to solve it, or any other method to create a pre-rendered map, my aim is then to display a subsection of this map in a smaller canvas.
Thanks.
change "map" to "canvas", and error will gone
var map_rendered = document.createElement("canvas");
map_rendered.heigt = 100 ;
map_rendered.width = 100 ;
var map_rendered_ctx = map_rendered.getContext("2d");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

capture div into image using html2canvas

I'm trying to capture a div into an image using html2canvas
I have read some similar question here like
How to upload a screenshot using html2canvas?
create screenshot of web page using html2canvas (unable to initialize properly)
I have tried the code
canvasRecord = $('#div').html2canvas();
dataURL = canvasRecord.toDataURL("image/png");
and the canvasRecord will be undefined after .html2canvas() called
and also this
$('#div').html2canvas({
onrendered: function (canvas) {
var img = canvas.toDataURL()
window.open(img);
}
});
browser gives some (48 to be exact) similar errors like:
GET http://html2canvas.appspot.com/?url=https%3A%2F%2Fmts1.googleapis.com%2Fvt%…%26z%3D12%26s%3DGalileo%26style%3Dapi%257Csmartmaps&callback=html2canvas_1 404 (Not Found)
BTW, I'm using v0.34 and I have added the reference file html2canvas.min.js and jquery.plugin.html2canvas.js
How can I convert the div into canvas in order to capture the image.
EDIT on 26/Mar/2013
I found Joel's example works.
But unfortunately when Google map embedded in my app, there will be errors.
<html>
<head>
<style type="text/css">
div#testdiv
{
height:200px;
width:200px;
background:#222;
}
div#map_canvas
{
height: 500px;
width: 800px;
position: absolute !important;
left: 500px;
top: 0;
}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false"></script>
<script type="text/javascript" src="html2canvas.min.js"></script>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script language="javascript">
$(window).load(function(){
var mapOptions = {
backgroundColor: '#fff',
center: new google.maps.LatLng(1.355, 103.815),
overviewMapControl: true,
overviewMapControlOptions: { opened: false },
mapTypeControl: true,
mapTypeControlOptions: { position: google.maps.ControlPosition.TOP_LEFT, style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
panControlOptions: { position: google.maps.ControlPosition.RIGHT_CENTER },
zoomControlOptions: { position: google.maps.ControlPosition.RIGHT_CENTER },
streetViewControlOptions: { position: google.maps.ControlPosition.RIGHT_CENTER },
disableDoubleClickZoom: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
minZoom: 1,
zoom: 12
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
$('#load').click(function(){
html2canvas($('#testdiv'), {
onrendered: function (canvas) {
var img = canvas.toDataURL("image/png")
window.open(img);
}
});
});
});
</script>
</head>
<body>
<div id="testdiv">
</div>
<div id="map_canvas"></div>
<input type="button" value="Save" id="load"/>
</body>
</html>
I ran into the same type of error you described, but mine was due to the dom not being completely ready to go. I tested with both jQuery pulling the div and also getElementById just to make sure there wasn't something strange with the jQuery selector. Below is an example that works in Chrome:
<html>
<head>
<style type="text/css">
div {
height: 50px;
width: 50px;
background-color: #2C7CC3;
}
</style>
<script type="text/javascript" src="html2canvas.js"></script>
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script language="javascript">
$(document).ready(function() {
//var testdiv = document.getElementById("testdiv");
html2canvas($("#testdiv"), {
onrendered: function(canvas) {
// canvas is the final rendered <canvas> element
var myImage = canvas.toDataURL("image/png");
window.open(myImage);
}
});
});
</script>
</head>
<body>
<div id="testdiv">
</div>
</body>
</html>
If you just want to have screenshot of a div, you can do it like this
html2canvas($('#div'), {
onrendered: function(canvas) {
var img = canvas.toDataURL()
window.open(img);
}
});
you can try this code to capture a div When the div is very wide or offset relative to the screen
var div = $("#div")[0];
var rect = div.getBoundingClientRect();
var canvas = document.createElement("canvas");
canvas.width = rect.width;
canvas.height = rect.height;
var ctx = canvas.getContext("2d");
ctx.translate(-rect.left,-rect.top);
html2canvas(div, {
canvas:canvas,
height:rect.height,
width:rect.width,
onrendered: function(canvas) {
var image = canvas.toDataURL("image/png");
var pHtml = "<img src="+image+" />";
$("#parent").append(pHtml);
}
});
10 2022
This question is quite old, but if anyone looking for a clear solution to implement then here it is. This is using Pure JS with html2canvas and FileSaver
I have tested and it works fine.
Capture everything inside a div.
Step 1
Include the scripts in your footer. jQuery is not needed, These two are fine. If you already have these two in your file, watch out for the correct version. I know it's a little thing, but it is important.
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js"></script>
Step 2
Basic div. The style attribute is optional. I am using it here to make it look presentable.
<div id="savethegirl" style="background-color:coral;color:white;padding:10px;width:200px;">
I am a Pretty girl 👩
</div>
<button onclick="myfunc()">Save the girl</button>
It should look like this
Step 3
Include this script
function myfunc(){
// if you are using a different 'id' in the div, make sure you replace it here.
var element = document.getElementById("savethegirl");
html2canvas(element).then(function(canvas) {
canvas.toBlob(function(blob) {
window.saveAs(blob, "Heres the Girl.png");
});
});
};
Step 4
Click the button and it should save the file.
Resources
CDN from: https://cdnjs.com/
This is from Carlos Delgado's article (https://ourcodeworld.com/articles/read/415/how-to-create-a-screenshot-of-your-website-with-javascript-using-html2canvas). I simplified it
If this answer is useful.
Hit that up arrow 🠉 It will help others to find it.
I don't know if the answer will be late, but I have used this form.
JS:
function getPDF() {
html2canvas(document.getElementById("toPDF"),{
onrendered:function(canvas){
var img=canvas.toDataURL("image/png");
var doc = new jsPDF('l', 'cm');
doc.addImage(img,'PNG',2,2);
doc.save('reporte.pdf');
}
});
}
HTML:
<div id="toPDF">
#your content...
</div>
<button id="getPDF" type="button" class="btn btn-info" onclick="getPDF()">
Download PDF
</button>
You can get the screenshot of a division and save it easily just using the below snippet. Here I'm used the entire body, you can choose the specific image/div elements just by putting the id/class names.
html2canvas(document.getElementsByClassName("image-div")[0], {
useCORS: true,
}).then(function (canvas) {
var imageURL = canvas.toDataURL("image/png");
let a = document.createElement("a");
a.href = imageURL;
a.download = imageURL;
a.click();
});
It can be easily done using html2canvas, try out the following,
try adding the div inside a html modal and call the model id using a jquery function. In the function you can specify the size (height, width) of the image to be displayed. Using modal is an easy way to capture a html div into an image in a button onclick.
for example have a look at the code sample,
`
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<div class="modal-body">
<p>Some text in the modal.</p>
`
paste the div, which you want to be displayed, inside the model. Hope it will help.
window.open didn't work for me... just a blank page rendered... but I was able to make the png appear on the page by replacing the src attribute of a pre-existing img element created as the target.
$("#btn_screenshot").click(function(){
element_to_png("container", "testhtmltocanvasimg");
});
function element_to_png(srcElementID, targetIMGid){
console.log("element_to_png called for element id " + srcElementID);
html2canvas($("#"+srcElementID)[0]).then( function (canvas) {
var myImage = canvas.toDataURL("image/png");
$("#"+targetIMGid).attr("src", myImage);
console.log("html2canvas completed. png rendered to " + targetIMGid);
});
}
<div id="testhtmltocanvasdiv" class="mt-3">
<img src="" id="testhtmltocanvasimg">
</div>
I can then right-click on the rendered png and "save as". May be just as easy to use the "snipping tool" to capture the element, but html2canvas is an certainly an interesting bit of code!
You should try this (test, works at least in Firefox):
html2canvas(document.body,{
onrendered:function(canvas){
document.body.appendChild(canvas);
}
});
Im running these lines of code to get the full browser screen (only the visible screen, not the hole site):
var w=window, d=document, e=d.documentElement, g=d.getElementsByTagName('body')[0];
var y=w.innerHeight||e.clientHeight||g.clientHeight;
html2canvas(document.body,{
height:y,
onrendered:function(canvas){
var img = canvas.toDataURL();
}
});
More explanations & options here: http://html2canvas.hertzen.com/#/documentation.html

Not able to load google map

I am trying to show the user's location obtained using geolocation API on google map.but the map is not loading.What am i doing wrong ?
$(document).ready(function(){
trackLocation()
})
//Track the user's location with high accuracy
function trackLocation(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(
successFunction,
errorFunction,
{enableHighAccuracy : true,
timeout:1000 * 10 * 100,
maximumAge:0
}
)
}
}
function successFunction(position){
plotMap(position)
}
function errorFunction(error){
alert(error)
}
function plotMap(position){
var location = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude)
alert('created locaction')
var plotOptions = {
center: location,
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
alert('created options')
var map = new google.maps.Map(document.getElementById('map_canvas'),plotOptions)
alert('created map')
}
and the html is
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="{{STATIC_URL}}jquery.min.js"></script>
<script type="text/javascript" src="{{STATIC_URL}}javascript_posted_above.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
</head>
<body>
Hi
<div id="map_canvas" style="width:100%; height:100%;"></div>
</body>
</html>
Take a look at this jsFiddle. The only differences between this and yours are the removal of the static js references and added the CSS. Without that CSS the map doesn't appear to display. I have never experienced this problem when using the Maps Api, perhaps I just added this CSS without thinking.
The CSS was taken from the HelloWorld tutorial on the docs.
here is my fiddle, I changed a few things:
First off all, I changed Alert to Console.log, which is important
since it is a non-obstructive way of logging, alert stops script
excecution and is not reliable.
I removed the google map script tag, and dynamically added it to the page in the document.ready handler, I also added a callback function "&callback=trackLocation", the JSON-P loaded script from Google will run the function with that name, when its executed.
I attached the function trackLocation(), directly to the window object, so it would be found by the script loaded from Google.
I changed the height of your map_canvas to 500px, instead of 100%, there seems to be an issue stretching a map. My first google search gave me: http://forum.jquery.com/topic/google-map-not-stretching-properly-when-width-set-to-100 you could do more research with that.
Good luck with your map!
Have you tried calling googlemap.js before your .js in the html?
I was loading the Google Maps API like this:
function mapsjsready()
{
// mapsjs ready!
}
$(document).ready( function() {
var mapsjs = document.createElement( 'script' );
mapsjs.type = "text/javascript";
mapsjs.async = true;
mapsjs.src = "https://maps.googleapis.com/maps/api/js?sensor=false";
mapsjs.id = "mapsjs";
mapsjs.onload = mapsjsready;
// Only for IE 6 and 7
mapsjs.onreadystatechange = function()
{
if( this.readyState == 'complete' )
{
mapsjsready();
}
}
document.body.appendChild( mapsjs );
});
But it suddenly stopped working.
I found that adding the callback parameter somehow solved the problem :
function mapsjsready()
{
// mapsjs ready!
}
function mapsjsloaded()
{
// mapsjs loaded!
}
$(document).ready( function() {
var mapsjs = document.createElement( 'script' );
mapsjs.type = "text/javascript";
mapsjs.async = true;
mapsjs.src = "https://maps.googleapis.com/maps/api/js?sensor=false&callback=mapsjsloaded";
mapsjs.id = "mapsjs";
mapsjs.onload = mapsjsready;
// Only for IE 6 and 7
mapsjs.onreadystatechange = function()
{
if( this.readyState == 'complete' )
{
mapsjsready();
}
}
document.body.appendChild( mapsjs );
});
I don't understand why, but adding the callback parameter solved my problem.

Google Map V3 context menu

I am looking for a Google Map V3 context menu library. I have found some code examples here
Gizzmo's blog
Google API tips
GMap3
How I got ..
Stack overflow question Google maps v3 - Contextual menu available? of April also just came up with the above examples. So did Gmap3 adding a simple context menu .
But maybe somebody has encapsulated the examples in a reusable library or found something in the meantime. Obviously there was something for V2.
-- Updated 2012-05-31 --
I have found another one http://googlemapsmania.blogspot.de/2012/04/create-google-maps-context-menu.html , but did not have the time to test it yet.
I don't think you need a library for this. I'd start by trying:
var contextMenu = google.maps.event.addListener(
map,
"rightclick",
function( event ) {
// use JS Dom methods to create the menu
// use event.pixel.x and event.pixel.y
// to position menu at mouse position
console.log( event );
}
);
This assumes your map was created with:
var map = new google.maps.map( { [map options] } );
The event object inside the callback has 4 properties
latLng
ma
pixel
where pixel.x and pixel.y are the offset where your click event triggered - counted from the upper left corner of the canvas holding the map object.
I have created a working JS Fiddle for showing context menu as well as the ability to have clickable items on this context menu.
It shows a clickable Context Menu when a marker is right clicked on Google map.
Basically it makes use of an OverlayView on map. BTW its just a demo.
var loc, map, marker, contextMenu;
ContextMenu.prototype = new google.maps.OverlayView();
/**
* onAdd is called when the map's panes are ready and the overlay has been
* added to the map.
*/
ContextMenu.prototype.onAdd = function() {
$("<div id='cMenu' class='context-menu-marker'></div>").appendTo(document.body);
var divOuter = $("#cMenu").get(0);
for(var i=0;i < this.menuItems.length;i++) {
var mItem = this.menuItems[i];
$('<div id="' + mItem.id + '" class="options-marker">' +
mItem.label + '</div>').appendTo(divOuter);
}
this.div_ = divOuter;
// Add the element to the "overlayLayer" pane.
var panes = this.getPanes();
//panes.overlayLayer.appendChild();
panes.overlayMouseTarget.appendChild(this.div_);
var me = this;
for(var i=0;i < this.menuItems.length;i++) {
var mItem = this.menuItems[i];
var func = function() {
me.clickedItem = this.id;
google.maps.event.trigger(me, 'click');
};
google.maps.event.addDomListener($("#" + mItem.id).get(0), 'click', $.proxy(func, mItem));
}
google.maps.event.addListener(me, 'click', function() {
alert(me.clickedItem);
});
};
ContextMenu.prototype.draw = function() {
var div = this.div_;
div.style.left = '0px';
div.style.top = '0px';
div.style.width = '100px';
div.style.height = '50px';
};
// The onRemove() method will be called automatically from the API if
// we ever set the overlay's map property to 'null'.
ContextMenu.prototype.onRemove = function() {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
};
// Set the visibility to 'hidden' or 'visible'.
ContextMenu.prototype.hide = function() {
if (this.div_) {
// The visibility property must be a string enclosed in quotes.
this.div_.style.visibility = 'hidden';
}
};
ContextMenu.prototype.show = function(cpx) {
if (this.div_) {
var div = this.div_;
div.style.left = cpx.x + 'px';
div.style.top = cpx.y + 'px';
this.div_.style.visibility = 'visible';
}
};
function ContextMenu(map,options) {
options = options || {}; //in case no options are passed to the constructor
this.setMap(map); //tells the overlay which map it needs to draw on
this.mapDiv = map.getDiv(); //Div container that the map exists in
this.menuItems = options.menuItems || {}; //specific to context menus
this.isVisible = false; //used to hide or show the context menu
}
function initialize() {
loc = new google.maps.LatLng(62.323907, -150.109291);
var options = {};
var menuItems=[];
menuItems.push({id:"zoomIn", className:'context_menu_item', eventName:'zoom_in_click', label:'Zoom in'});
menuItems.push({id:"zoomOut", className:'context_menu_item', eventName:'zoom_out_click', label:'Zoom out'});
options.menuItems = menuItems;
//=========================================
map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: loc,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
marker = new google.maps.Marker({
map: map,
position: loc,
visible: true
});
contextMenu = new ContextMenu(map, options);
google.maps.event.addListener(marker, 'rightclick', function(mouseEvent){
contextMenu.hide();
this.clickedMarker_ = this;
var overlayProjection = contextMenu.getProjection();
var cpx = overlayProjection.fromLatLngToContainerPixel(mouseEvent.latLng);
contextMenu.show(cpx);
map.setOptions({ draggableCursor: 'pointer' });
});
// Hide context menu on several events
google.maps.event.addListener(map,'click', function(){
map.setOptions({ draggableCursor: 'grab' });
contextMenu.hide();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Fiddle link:
http://jsfiddle.net/jEhJ3/3409/
You can add context menu very easily in google map by following these steps:
Add a custom control of google maps, hide that control on page load.
Add a right click event handler on map.
Show that custom control on right click at correct position using pixel property of right click event parameter.
Moreover, Following is working snippet, open it in full page (use you own key to avoid that google billing error):
var map;
var karachi = {
lat: 24.8567575,
lng: 66.9701725
};
$(document).ready(function() {
initMap();
});
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 13.5,
center: karachi
});
let contextMenu = document.getElementById('contextMenu');
map.controls[google.maps.ControlPosition.TOP_CENTER].push(contextMenu);
hideContextMenu();
google.maps.event.addListener(map, "rightclick", function(event) {
showContextMenu(event);
});
google.maps.event.addListener(map, "click", function(event) {
hideContextMenu();
});
}
function showContextMenu(event) {
$('#contextMenu').css("display", "block");
$('#contextMenu').css({
left: event.pixel.x,
top: event.pixel.y
})
}
function hideContextMenu() {
$('#contextMenu').css("display", "none");
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
.contextMenu {
background-color: rgb(255, 255, 255);
border: 2px solid rgb(255, 255, 255);
border-radius: 3px;
box-shadow: rgba(0, 0, 0, 0.3) 0px 2px 6px;
cursor: pointer;
font-size: 1rem;
text-align: center;
color: #0d1f49;
width: 20vw;
margin: 1px;/*Please note that this margin is necessary otherwise browser will open its own context menu*/
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAGlM3LLIL2j4Wm-WQ9qUz7I7ZpBsUx1X8">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="map"></div>
<div id="contextMenu" class="contextMenu">
<div onclick="alert('On click of item 1 is called')">
Item 1
</div>
</div>
Go to this demo-purpose website: http://easysublease.org/mapcoverjs/
For context menu, I do not suggest implementing one subclass of the overlayView Class provided by Google Maps API. First, one instance of subclass of overlayView should be added to the five panes provided by Google. More possibly one should add this instance to pane overlayMouseTarget .
But, this instance is "shadowed" by other dom over it. So normal original browser event such mouseover, mouseout cannot reach this instance.
One must use Google Maps API method: addDomListener to handle it(why?). It requires lots of JavaScript code to implement different event handlers, do lots of css class adding and deleting just to realize some visual effects, which could be done using several lines of CSS code if this instance is outside the map container.
So actually converting one external dom outside google map container into one context menu has merit that it can receive original DOM events from browser. Also using some external library can make the target behave better. As context menu, it should not only be able to handle original events, but also those events from Map.
-----------see implementations below------------------------
At the map part HTML, this is the code:
<div id="mapcover">
<div id="mapcover-map"></div> <!-- this is map container-->
<div id="demoControlPanel" class="mc-static2mapcontainer panel">I am map UI control button's container, I think one can use jQuery UI to make me look better<br><br>
<div id="zoom-in-control" class="text-center">zoomIn</div>
<div id="zoom-out-control" class="text-center">zoomOut</div>
</div>
<div id="demoContextPanel" class="mc-ascontextmenu panel">
I am map context menu container, you can sytle me and add logic to me, just as normal DOM nodes.
since I am not in Map Container at all!
<div class="text-center">
<div role="group" aria-label="..." class="btn-group">
<button id="place-marker1" type="button" class="btn btn-default">Marker1</button>
<button id="place-marker2" type="button" class="btn btn-default">Marker2</button>
</div>
</div>
<div class="form-group">
<label for="content-marker1">Content of next Marker1</label>
<input id="content-marker1" type="text" placeholder="New of Marker1!" class="form-control">
</div>
</div>
</div>
It shows how one developer can convert one external DOM (id=demoContextPanel) into one map context menu by just adding one css class ".mc-ascontextmenu"!
That pages uses mapcover.js, which helps developer to manage some key components of Map such as Map control UIs, context menu, and customized markers. Then Developers have full freedom to style its map UIs.
If you need more, you can go to its Github see readme.md: https://github.com/bovetliu/mapcover

Strange bug with OpenLayers + CloudMade

I am trying something fairly simple, you can see a demo here:
http://www.jsfiddle.net/VVe8x/19/
This bug only appears in Firefox, so to see it press either one of the links once (it will take you to either NY or Israel) then press the other link.
The bug is that it will not show me the tiles in that location, instead it will show me the background of the div.
P.S In Chrome this works flawlessly.
I dont know if this is a clue or it might confuse you, if in between pressing either NY or Israel links you press the "view the world" link it will allow you then to see the other location..
Full Source for reference
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<body>
show me NY
show me TLV
show world map(a "workaround"
<div id='myMap' style="height: 600px; width: 600px; position: relative"></div>
<script src="http://openlayers.org/api/OpenLayers.js" type="text/javascript"></script>
<script src="http://developers.cloudmade.com/attachments/download/58/cloudmade.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
map = new OpenLayers.Map("myMap", {
controls: [
new OpenLayers.Control.Navigation(),
new OpenLayers.Control.PanZoomBar()
]
});
var cloudmade = new OpenLayers.Layer.CloudMade("CloudMade", {
key: 'd5da652e33e6486ba62fca3d18ba70c9'
});
map.addLayer(cloudmade);
var epsg4326 = new OpenLayers.Projection("EPSG:4326");
map.setCenter(new OpenLayers.LonLat(40, 32), 2);
show1 = function(){
var bound1 = new OpenLayers.Bounds(-8236567.917898,4972686.066032,-8236148.409989,4972889.624407);
map.zoomToExtent(bound1); // to NY
};
show2 = function(e){
var bound2 = new OpenLayers.Bounds(3874818.203389,3773932.267033,3875217.305962,3774226.370443);
map.zoomToExtent(bound2); // to Israel
return false;
};
</script>
</body>
</html>
The myMap_OpenLayers_Container has the following CSS when the tiles are invisible:
position: absolute; z-index: 749; left: -2.02815e+7px; top: -2007340px;
If you change these around you can see that the correct tiles were loaded, so its likely to be jsFiddle messing them up. The tiles CSS when they don't show also have strange values.
Update:
Testing locally also produces the issue, so that rules out jsFiddle.
A fix would be to set this value after the zoom by calling a function such as:
updateCSS = function(){
OpenLayers_Container = document.getElementById("myMap_OpenLayers_Container").style.left = "0px";
}
This looks like a bug, although if it is in OpenLayers or the CloudMade layer properties is hard to tell - I'd imagine the latter, or it would be a widely reported bug. The relevant code in OpenLayers.js appears to be:
centerLayerContainer: function(lonlat){
var originPx = this.getViewPortPxFromLonLat(this.layerContainerOrigin);
var newPx = this.getViewPortPxFromLonLat(lonlat);
if ((originPx != null) && (newPx != null)) {
this.layerContainerDiv.style.left = Math.round(originPx.x - newPx.x) + "px";
this.layerContainerDiv.style.top = Math.round(originPx.y - newPx.y) + "px";
}
I was running into this problem too, and it turned out I was not setting the map's center as I thought I was. The problem goes away if you first call map.setCenter(). For example:
var newCenter = new OpenLayers.Lonlat(longitude, latitude)
.transform(new OpenLayers.Projection('ESPG:4326'),
this.map.getProjectionObject());
this.map.setCenter(newCenter);
Hope this helps whoever next has the problem.

Categories

Resources