As you can see at:
http://rolls.mit.edu/
I am doing the following:
create a map
map = new google.maps.Map(mapContainer, options);
add overlay
overlay = new google.maps.OverlayView();
overlay.draw = function() {};
overlay.setMap(map);
add canvas to overlay
overlay.getPanes().overlayLayer.appendChild(canvas);
Everything works well except when I zoom, the canvas remains the same size. Is it possible to zoom the canvas when you zoom in/out? Any pointers to examples?
You need to listen to the google.maps.Map zoom_changed event, get the new zoom level from the map (with map.getZoom()), then resize or modify your canvas element appropriately.
If you just want to draw a line, look at the google.maps.Polyline overlay, that has the zoom functionality built in.
You pretty much have to render a new canvas for whatever google zoom levels you want to support. The way I have addressed this is by setting a listener on the "idle" event for the map. This will fire once the map goes idle after a zoom or pan. Then you can determine if the zoom level has changes and act accordingly.
var map = new google.maps.Map(mapContainer, options);
var zoomLevel = 6; //some defaut
var handleBoundsChanged = function(){
var oldZoom = zoomLevel;
var zoomLevel = map.getZoom();
if( zoomLevel != oldZoom){
rebuildOverlayForZoom(zoomLevel)
}
}
google.maps.event.addListener (map, 'idle', handleBoundsChanged);
Related
I am using Mapbox GL JS and created a dynamic store locator based on their store locator demo. I am using fitBounds to include all store markers on the initial display of the map.
The problem is, it zooms in too close and the map needs a bit of padding. So, I'm trying to back out the zoom one level. The problem is, when I get the zoom level and back out one, the map is recentered to the original center of the map.
I have included code below where I try to reset the center to the fitBounds center but it's not working. Any idea what I'm doing wrong?
var bounds = new mapboxgl.LngLatBounds();
$(markers).each(function() {
var features = $(this);
bounds.extend(features[0].geometry.coordinates);
});
map.fitBounds(bounds);
var mapLat = map.getBounds().getCenter().lat;
var mapLong = map.getBounds().getCenter().long;
map.setCenter = (mapLat, mapLong);
var mapZoom = map.getZoom();
newZoom = mapZoom - 1;
map.setZoom(newZoom);
If all you want to achieve is to add padding to the bounds, mapbox-gl provides an option for this in fitBounds:
map.fitBounds(bounds, {padding: 100}) // adds 100px padding to the bounds
Here is the documentation: https://www.mapbox.com/mapbox-gl-js/api#map#fitbounds
So I'm using the latest version of leaflet (v1.0.2), and am trying to dynamically apply text labels to specific lat lng points on a custom (geo aligned) map.
My issue is that I need the text on the map to maintain it's the size (as though the text is actually part of the tile image) when zooming. Using a Marker of any kind results in the text staying at its correct size. If I use something like an image overlay and add an SVG with text in, it scales with the map zoom.
I've noticed that the image overlay has a CSS3 scale added to its transform property when zooming whereas the marker does not.
Can I extend the marker to scale as the image overlay does?
I've already written code that listens to the zoom event and adjusts the font size of markers but this is CPU intensive (especially for mobile browsers) and I don't really want to render the text dynamically within svgs either!
I've provided a demo so that this makes more sense. You can see that example_1 (the marker) maintains it's size however far you zoom in or out. Example_2 (the svg image) scales relative to the map when zooming. This (Example_2) is what I'm trying to get an L.DivIcon with html text content to do!
Any help or suggestions are appreciated!
https://jsfiddle.net/z96L7hdu/
Example Code
HTML
<div id="map" style="width:500px; height:600px;"></div>
JavaScript
var map = L.map('map', {
zoomSnap: 0
}).setView([0, 0], 3);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var img = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciICAgICB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiB2aWV3Qm94PSIwIDAgNTAwIDQwIj4gIDx0ZXh0IHg9IjAiIHk9IjAiIGZvbnQtZmFtaWx5PSJWZXJkYW5hIiBmb250LXNpemU9IjM1Ij4gICAgRXhhbXBsZV8yICA8L3RleHQ+PC9zdmc+";
imageBounds = [[-8.636810901898114, -12.135975261193327], [-18.28136415046407, 17.181122017133486]];
L.imageOverlay(img, imageBounds).addTo(map);
var myIcon = L.divIcon({className: 'my-div-icon', html:"Example_1"});
L.marker({lat: 0.7800052024755708, lng: 0.010986328125}, {icon: myIcon}).addTo(map);
Apologies for the late answer, but I thought it was an interesting question. You can indeed extend the L.Marker class, to create markers that resize the font of their DivIcon to match the zoom level:
L.FixedSizeMarker = L.Marker.extend({
options: {
fontSize: 12, // starting size of icon in pixels
zoomBase: 3 // Zoom level where fontSize is the correct size
},
update: function () {
if (this._icon && this._icon.tagName === 'DIV' && this._map) {
let size = this.options.fontSize * Math.pow(2, (this._map.getZoom() - this.options.zoomBase));
this._icon.style.fontSize = size + 'px';
}
return L.Marker.prototype.update.call(this);
}
});
L.fixedSizeMarker = (latlng, options) => new L.FixedSizeMarker(latlng, options);
The code above defines a new FixedSizeMarker, which behaves just like a normal Marker, but if you add a DivIcon to it, it will resize the font. It takes two options, to specify the font size in pixels, and the zoom level that you want that font size to be correct for. In the example in the OP's JSFiddle, you would use it like this:
var myIcon3 = L.divIcon({className: 'my-div-icon', html:"Example_3"});
L.fixedSizeMarker({lat: 0.7800052024755708, lng: -12.135975261193327},
{icon: myIcon3, fontSize: 24, zoomBase: 3}).addTo(map);
When using these markers, it may look better to set {markerZoomAnimation: false} in the map options. The marker size change is otherwise quite obvious when you zoom the map.
const element = marker.getElement();
element.style[L.DomUtil.TRANSFORM] = `scale(3)`;
You can use this to modify the css of a marker
I am using Google Maps API V3 for JavaScript, I do like to get a Marker's position relatively to my page in pixels (left, top), so I can add a custom label when hoving the mouse over my marker. How do I get that position?
If your referring to getting the position of your mouse while you hover, use overlay in the listener to get the projection and the pixel coordinates. Overlays are objects on the map that are tied to latitude/longitude coordinates, so they move when you drag or zoom the map. If you want to place an image on a map, you can use a GroundOverlay object or you can create your own Custom Overlays with the use of OverlayView class.
Sample code using OverlayView:
var overlay = new google.maps.OverlayView();
overlay.draw = function() {};
overlay.setMap(map); // 'map' is new google.maps.Map(...)
With the Google Maps API (v3) I've created a custom map type for a fictional game world. By default, maps, even custom map types, repeat horizontally (see image below).
Larger Image here
Is it possible to keep the map from repeating horizontally? For my map, it does not represent a planet or spherical world, so having it repeat horizontally forever doesn't make sense at all. I have figured out how to simply not load tiles for the repeated maps on the left and right like so:
Larger Image here
HOWEVER, when you create markers, the markers still show up for all the repeated maps:
Larger Image here
Is it possible to keep the markers from repeating? Or is it possible to keep the map from repeating at all? That way I don't have to deal with markers repeating?
Work Around: Limit Panning beyond the Map Bounds
I've read various work-arounds that discuss simply limiting how far the user can pan to the left or right. This won't work for me because I have to allow the user to zoom all the way out and view the entire map at once. If they zoom all the way out, repeated markers are still visible, which is unacceptable.
Is it possible to adding a bunch of padding to the map? That way there is a large amount of space between the maps:
Larger Image here
If I was able to add enough padding, then limiting the panning would work for me, because any repeated markers could be pushed far enough away by the padding that the user would never see them.
Finally my code, pretty simple:
(note: the map tile images I'm using are not available online yet)
<!DOCTYPE html>
<html style='height: 100%'>
<head>
<link rel="stylesheet" type="text/css" href="normalize.css" />
<style>
html, body { height: 100%;}
#map_canvas { height: 1000px;}
</style>
</head>
<body style='height: 100%'>
<div id="map_canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type='text/javascript'>
var options =
{
getTileUrl: function(coord, zoom)
{
// Don't load tiles for repeated maps
var tileRange = 1 << zoom;
if ( coord.y < 0 || coord.y >= tileRange || coord.x < 0 || coord.x >= tileRange )
return null;
// Load the tile for the requested coordinate
var file = 'images/zoom' + zoom + '/tile_' + zoom + '_' + (coord.x) + '_' + (coord.y) + '.jpg';
return file;
},
tileSize: new google.maps.Size(256, 256),
minZoom: 1,
maxZoom: 9,
radius: 1738000, // I got this from an example in the api, I have no idea what this does
name: 'Map',
};
var mapOptions =
{
center: new google.maps.LatLng(0,0),
zoom: 2,
backgroundColor: '#000',
streetViewControl: false,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
var mapType = new google.maps.ImageMapType(options);
map.mapTypes.set('map', mapType);
map.setMapTypeId('map');
var marker = new google.maps.Marker({
position: new google.maps.LatLng(0,0),
map: map,
title: "Test"
});
</script>
</body>
</html>
In answer to the question: Is it possible to keep the markers from repeating?
Yes.
From Google Maps JavaScript API V3 Reference (3.19), if you set the markerOptions property optimized to false for your marker, it does not repeat but only shows up on the center map.
See: https://developers.google.com/maps/documentation/javascript/reference#MarkerOptions
So, in your code, I would modify var marker as such (adding optimized: false):
var marker = new google.maps.Marker({
position: new google.maps.LatLng(0,0),
map: map,
title: "Test"
optimized: false
});
According to Google's docs (I've added the bolding),
Optimization renders many markers as a single static element. Optimized rendering is enabled by default. Disable optimized rendering for animated GIFs or PNGs, or when each marker must be rendered as a separate DOM element (advanced usage only).
I set optimized to false and then looked through the page to find the id (or at least class) associated with my markers. I was going to make the "extra" markers non-visible. It turns out the elements are there but have no id or class. Just as I was contemplating other ways to identify them using jQuery, I happened to look up at my "map" and realized the "extra" markers were gone! ☺
A word of caution: based on Google's docs, I suspect this behavior (the "extra" markers not showing up) may be an unintended "feature".
Cheers,
Bruce.
Looks to me like you just need to change your starting zoom and min zoom limit.
Even google runs into repeats when you are at zoom level 1, but it doesn't let you zoom out lower than that.
Just add minZoom and maxZoom properties to your options object to limit the zooming.
You can try to put a mask on the repeated area but I didn't tried it. This looks like it can solve your problem: Apply mask to Google Map.
Update: Apply the mask only when you need it, i.e. when the zoom is the lowest. I don't think resizeing the browser window will affect anything in the map. It's also has nothing to do with the question and the problem is if the mask lays on top of the marker.
Update 2: It's seems to be possible with v2 but not with v3. In v2 you can disable horizontal copies in the projection class: Google Maps API v3 with custom map image - markers repeating horizontally.
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 !
I'm wondering how I get a smooth zoom in animation with the Google Maps API.
I have 2 points, one in, let say China, and one in France. When I'm zoomed in on China, and click the button France. I want it to gradually zoom out smooth, one zoom level at the time. When it's zoomed out it should pan to the new location, and then zoom in on the new location one zoom level at the time.
How can I do this?
You need the zoomOut method with the continuous zoom parameter set to do the zoom and the panTo method to do the smooth panning to the new centerpoint.
You can listen to the zoomEnd and moveEnd events on the map object to chain together your zoomOut, panTo and zoomIn methods.
EDIT:
So in the course of implementing a sample for this problem, I discovered that the doContinuousZoom param on ZoomIn and ZoomOut (or just EnableContinuousZoom on the map) doesn't quite work as expected. It works ok when zooming out, if the tiles are in the cache (this is an important point, if the tiles aren't cached then it is not really possible to get the smooth animation you are after) then it does some nice scaling on the tiles to simulate a smooth zoom animation and introduces a ~500 ms delay on each zoom step so you can do it asynchronously (unlike panTo, which you will see in my example I use a setTimeout to call async).
Unfortunately the same is not true for the zoomIn method, which just jumps to the target zoom level without the scaling animation for each zoom level. I haven't tried explicitly setting the version for the google maps code, so this might be something that is fixed in later versions. Anyway, here is the sample code which is mostly just javascript hoop jumping and not so much with the Google Maps API:
http://www.cannonade.net/geo.php?test=geo2
Because this approach seems a bit unreliable, I think it would make more sense to do the async processing for setZoom explicitly (Same as the panning stuff).
EDIT2:
So I do the async zooming explicitly now (using setTimeout with a single zoom at a time). I also have to fire events when each zoom happens so that my events chain correctly. It seems like the zoomEnd and panEnd events are being called synchronously.
Setting enableContinuousZoom on the map doesn't seem to work, so I guess calling zoomOut, zoomIn with the param is the only way to get that to work.
Here's my approach.
var point = markers[id].getPosition(); // Get marker position
map.setZoom(9); // Back to default zoom
map.panTo(point); // Pan map to that position
setTimeout("map.setZoom(14)",1000); // Zoom in after 1 sec
var zoomFluid, zoomCoords; //shared variables
function plotMarker(pos, name){
var marker = new google.maps.Marker({
map: map,
title:name,
animation: google.maps.Animation.DROP,
position: pos
});
google.maps.event.addListener(marker, 'click', function(){
zoomCoords = marker.getPosition(); //Updates shared position var
zoomFluid = map.getZoom(); //Updates shared zoom var;
map.panTo(zoomCoords); //initial pan
zoomTo(); //recursive call
});
}
// increases zoomFluid value at 1/2 second intervals
function zoomTo(){
//console.log(zoomFluid);
if(zoomFluid==10) return 0;
else {
zoomFluid ++;
map.setZoom(zoomFluid);
setTimeout("zoomTo()", 500);
}
}
For the zoom this one worked for me nicely:
function animateMapZoomTo(map, targetZoom) {
var currentZoom = arguments[2] || map.getZoom();
if (currentZoom != targetZoom) {
google.maps.event.addListenerOnce(map, 'zoom_changed', function (event) {
animateMapZoomTo(map, targetZoom, currentZoom + (targetZoom > currentZoom ? 1 : -1));
});
setTimeout(function(){ map.setZoom(currentZoom) }, 80);
}
}