Hi I want to draw a line (free-form, Photoshop pencil / paintbrush style) over Google maps.
What would be the best way to do it?
How complicated would it be to do this AND keep the zoom option (so that line scales / disappears when the map is scaled)?
Which would be the best library to use for that (canvas? svg? something else)?
You could use the built indrawing tools, but if I recall correctly, you would need to click quite a bit to get a free form line.
Here's another pretty rough idea. Capture the mouse coordinates of the map container, grab the latLng from a google.maps.MapCanvasProjection and push the coordinates to a polyline path.
var map;
var elevator;
var myOptions = {
zoom: 6,
center: new google.maps.LatLng(46.87916, -3.32910),
mapTypeId: 'terrain'
};
map = new google.maps.Map($('#map')[0], myOptions);
var markers = [];
var isDrawing = false;
var overlay = new google.maps.OverlayView();
overlay.draw = function () {};
overlay.setMap(map);
// Add a listener for idle event and call getElevation on a random set of marker in the bound
google.maps.event.addListener(map, 'click', function () {
var polyLine = new google.maps.Polyline({
map: map
});
$("#map").mousemove(function (e) {
var pageX = e.pageX;
var pageY = e.pageY;
var point = new google.maps.Point(parseInt(pageX), parseInt(pageY));
var latLng = overlay.getProjection().fromDivPixelToLatLng(point);
polyLine.getPath().push(latLng);
});
});
Related
I need to draw polygon with just four coordinates that is for the four corners of the loaded map in zoom 13 on other hand get coordinates of the whole map to show to user. ( user search the specific area with draw a polygon on the map but if he/she don't draw a polygon i want to draw a polygon in size of the projected map for him/her and show the result. )
Create the map at zoom: 13
var map = new google.maps.Map(document.getElementById("map"), {
center: {lat: 51.561162, lng: -0.163331},
zoom: 13
});
Then use map.getBounds() to get the LatLngBounds of the visible map.
var bounds = map.getBounds();
You can then use this to get the LatLng coordinates of the South West and North East corners:
var NECorner = bounds.getNorthEast();
var SWCorner = bounds.getSouthWest();
Then you can use those to work out the coordinates for the other two corners:
var NWCorner = new google.maps.LatLng(NECorner.lat(), SWCorner.lng());
var SECorner = new google.maps.LatLng(SWCorner.lat(), NECorner.lng());
And finally draw the polygon, using those corners for the paths array:
var polygon = new google.maps.Polygon({
map: map,
paths: [NWCorner, NECorner, SECorner, SWCorner],
fillColor: 'red',
fillOpacity: 0.7
});
Thanks duncan
Lemme write it in short form for Kotlin developers
var bounds = googleMap!!.projection.visibleRegion.latLngBounds
var neCorner = bounds.northeast
var swCorner = bounds.southwest
var nwCorner = LatLng(neCorner.latitude, swCorner.longitude)
var seCorner = LatLng(swCorner.latitude, neCorner.longitude)
My problem is that when my map is loaded at that time I want to get X and Y cordinates of all four corners of screen as per resolution. My code:
map = new OpenLayers.Map("mapdiv", {
controls: [new OpenLayers.Control.Navigation(),
new OpenLayers.Control.PanZoomBar()
],
numZoomLevels: 10
});
map.addLayer(new OpenLayers.Layer.OSM("OpenCycleMap"));
epsg4326 = new OpenLayers.Projection("EPSG:4326");
epsg900913 = new OpenLayers.Projection("EPSG:900913");
var lonLat = new OpenLayers.LonLat(72.58, 23.03).transform(epsg4326, epsg900913);
console.log(lonLat);
var zoom = 15;
var markers = new OpenLayers.Layer.Markers("Markers");
map.addLayer(markers);
map.events.register("click", map, function (e) {
var lonlat = map.getLonLatFromViewPortPx(e.xy);
alert(lonlat);
});
markers.addMarker(new OpenLayers.Marker(lonLat));
var polygonLayer = new OpenLayers.Layer.Vector("Polygon Layer");
map.addLayer(polygonLayer);
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.addControl(new OpenLayers.Control.MousePosition());
map.setCenter(lonLat, zoom);
You should try to post a fiddle when you can. Assuming you're using OpenLayers v2.
If you meant to ask how to get the corners of the viewport, try:
map.getViewport().getClientRects()[0]
If you meant the extent of the map in coordinates:
map.getExtent()
I have a google map, and an marker on it.
I need the marker to be a fixed size of, for example, 10x10 pixels, and remail the same even if i zoom in or zoom out.
This is what i have right now (and is not workig):
var marker = new google.maps.Marker({
position: circleCenter,
map: googleMap,
icon: {
path: google.maps.SymbolPath.CIRCLE,
fillOpacity: 0.5,
fillColor: 'ff0000',
strokeWeight: 10,
size: 5
}
});
Is this possible to block the marker of scaling it's size when the map zoom is changed?
Google does not have a out-of-box way to stop markers from scaling.
You could use a Ground Overlay to set a fixed area on the map and then attach an image. The trick with ground overlays is you have to know the coordinates of the bounds object and you probably will have to come up with some way of calculating the bounds. In this example I just expand a center point into a rectangle.
You would also loose other marker capabilities since this method doesn't use a marker object (e.g. dragging, animations, etc.), but the overlays do have click events.
Here is a proof of concept: http://jsfiddle.net/bryan_weaver/4rxqQ/
relevant code:
function initialize() {
var map;
var centerPosition = new google.maps.LatLng(38.713107, -90.42984);
var options = {
zoom: 9,
center: centerPosition,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($('#map')[0], options);
var icon = 'https://www.google.com/mapfiles/marker_black.png';
var iconBounds = constructBounds(38.713107, -90.42984);
var staticOverlay = new google.maps.GroundOverlay(icon, iconBounds);
staticOverlay.setMap(map);
}
function constructBounds(lat, lng){
var sw = new google.maps.LatLng(lat - .03, lng - .025)
var ne = new google.maps.LatLng(lat + .03, lng + .025)
return new google.maps.LatLngBounds(sw, ne);
}
Im try to get the markers coordinates to the map, or to the window, to set a special functions when i make over with the mouse, my test code is this:
var multiMarker = [];
var xmyOptions = { // Ponemos unas coordenadas iniciales al mapa de google maps.
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var xmap = new google.maps.Map($('#map_canvas2').get(0), xmyOptions); // Iniciamos el mapa indicando el Div donde se va a cargar y las opciones.
for (x=0; x<9; x++) {
multiMarker[x] = new google.maps.Marker({ // Definimos una nueva "marca" o puntero
position: new google.maps.LatLng('40.' + Math.floor(Math.random()*99999999), '-3.' + Math.floor(Math.random()*99999999)),
draggable: true,
map: xmap,
title: 'Ejemplo marcador arrastrable'
});
google.maps.event.addListener(multiMarker[x], 'mouseover', function(){
console.log(this);
});
}
var bounds = new google.maps.LatLngBounds();
for (index in multiMarker) {
var data = multiMarker[index];
bounds.extend(new google.maps.LatLng(data.position.Oa, data.position.Pa));
}
xmap.fitBounds(bounds);
The problem is i cant get this coordinates in the marker[x] object, i only see the latitude and longitude, and I need the top, left, bottom or right position of the marker to set special floating tooltips. The API doesnt have this info?
Thanks.
I answered similar question here: How to access Google Maps API v3 marker's DIV and its pixel position?
What you can get is position of marker in world coordinate, then convert to offset from top left corner of visible rectangle. But it's only position, you don't have access to marker itself, so you can't add events to it or alter marker div this way.
var scale = Math.pow(2, map.getZoom());
var nw = new google.maps.LatLng(
map.getBounds().getNorthEast().lat(),
map.getBounds().getSouthWest().lng()
);
var worldCoordinateNW = map.getProjection().fromLatLngToPoint(nw);
var worldCoordinate = map.getProjection().fromLatLngToPoint(marker.getPosition());
var pixelOffset = new google.maps.Point(
Math.floor((worldCoordinate.x - worldCoordinateNW.x) * scale),
Math.floor((worldCoordinate.y - worldCoordinateNW.y) * scale)
);
If for some reason you need access to marker's div, then you need to check what divs are created for map, select in which layer (markers are in one layer, but I don't remember which, don't confuse them with marker shadows :-)) and then somehow check which position this divs have, to select one you need.
I got a basic map running using google maps v3
Next features that I would like to add include:
draw line as road directions instead of direct point to point polyline
draw a circle 75 km circle around from a specific point
highlight the postal code of a specific point.
I Would appreciate people's thoughts on these topics
var geocoder;
var map;
function fnPresentMap()
{
geocoder = new google.maps.Geocoder();
var locationArray = new Array();
locationArray[0] = new Array();
locationArray[1] = new Array();
locationArray[0][0] = document.getElementById('LAT_OUT_1').innerHTML;
locationArray[0][1] = document.getElementById('LON_OUT_1').innerHTML;
locationArray[1][0] = document.getElementById('LAT_OUT_2').innerHTML;
locationArray[1][1] = document.getElementById('LON_OUT_2').innerHTML;
var latlng = new google.maps.LatLng(44, -75);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
var myLatlng;
var image_name;
for (var count = 0; count < locationArray.length; ++count){
image_name = "img/marker_"+(count+1)+".png";
myLatlng = new google.maps.LatLng(locationArray[count][0],locationArray[count][1]);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: image_name
});
}
// re-center
var centerLocation = new google.maps.LatLng(locationArray[0][0],locationArray[0][1]);
map.setCenter(centerLocation);
// show line
var points = [
new google.maps.LatLng(locationArray[0][0],locationArray[0][1]),
new google.maps.LatLng(locationArray[1][0],locationArray[1][1])
];
var line = new google.maps.Polyline({
map: map,
path: points,
strokeColor: "#FF0000",
strokeWeight: 2,
strokeOpacity: 1.0
});
}
To render road directions between two specific points, you need to use the Google Maps API directions service. If you check out the documentation you will find pretty straightforward examples to make a directions request and render the results on a map as a line between the two points.
I think the best approach for drawing a circle around a point is to draw a polygon with enough points to approximate a circle. You can find a good example of this here.
To highlight the postcode at a specific point, I suggest you use the Google Maps API reverse geocoding service (convert from a latitude/longitude to a human readable address). You can extract the postcode from the JSON response you get back and then display it on the map using a infoWindow or some other kind of overlay.