I have a bound value returned by getBounds() google map API as under -
**_.pe {pa: oe, ka: ke}
ka: ke {g: -180, h: 180}
pa: oe {g: -26.222936261748305, h: 72.98776122961861}
__proto__: Object**
On googling I found out that we can get use getSouthWest() and getNorthEast() apis to decode the
above information to get desired co-ordinates, but unfortunately its not working for me.
I get the following output -
**console.log(vr.getNorthEast())
VM312861:1
_.L {lat: ƒ, lng: ƒ}
lat: ƒ ()
lng: ƒ ()
__proto__: Object**
Any ideas how to fix this or any other method that I can use to get co-ordinates from bounds.
Thanks
getNorthEast and getSouthWest return LatLng objects. To get the raw values from these objects, you could use the following functions on a LatLng object to get the coordinates: .lat() for latitude, .lng() for longitude, or .toString() for a string representation of the coordinates.
Also, note that the map must be initialized or the bounds will be undefined.
Here's a working example. You can ignore the initial script error, which is due to not using an API key. Just drag the map to see the coordinates appear in the console for all four corners:
let map;
function initialize() {
let mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
map.addListener("dragend", function() {
let bounds = map.getBounds();
let ne = bounds.getNorthEast(); // Coords of the northeast corner
let sw = bounds.getSouthWest(); // Coords of the southwest corner
let nw = new google.maps.LatLng(ne.lat(), sw.lng()); // Coords of the NW corner
let se = new google.maps.LatLng(sw.lat(), ne.lng()); // Coords of the SE corner
console.log(ne.toString(), sw.toString(), nw.toString(), se.toString());
})
}
google.maps.event.addDomListener(window, 'load', initialize);
#map-canvas {
height: 500px;
margin: 0px;
padding: 0px;
width: 500px;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<div id="map-canvas"></div>
Related
My code puts a marker on the map each time I click on it.
The objective is to get each time marker's lat/lon coordinates together with pixel coordinates. So far I've been successful only in getting lat/lon coord. The next step now would be taking these as input and compute the pixel coordinates.
<script>
function initMap() {41.85, -87.65
var myLatlng = {lat: 41.85, lng: -87.65};
var map = new google.maps.Map(
document.getElementById('map'), {zoom: 18,
center: myLatlng,
disableDefaultUI: false,
mapTypeId: 'satellite',
zoomControl: true,
mapTypeControl: true,
scaleControl: true,
streetViewControl: false,
rotateControl: false,
fullscreenControl: true});
map.setOptions({draggableCursor:'default'});
map.addListener('click', function(marker){
marker = new google.maps.Marker({map: map,
clickable: false,
position: marker.latLng,
})
var markerposLat = marker.getPosition().lat();
var markerposLon = marker.getPosition().lng();
function pixl(markerposLat,markerposLon){
var projection = map.getProjection();
var bounds = map.getBounds();
var topRight = projection.fromLatLngToPoint(bounds.getNorthEast());
var bottomLeft = projection.fromLatLngToPoint(bounds.getSouthWest());
var scale = Math.pow(2, map.getZoom());
var worldPoint = projection.fromLatLngToPoint(markerposLat,markerposLon);
return [Math.floor((worldPoint.x - bottomLeft.x) * scale), Math.floor((worldPoint.y - topRight.y) * scale)]
};
localStorage["pixl"] = JSON.stringify(pixl);
localStorage["markerLat"] = JSON.stringify(markerposLat);
localStorage["markerLon"] = JSON.stringify(markerposLon);
console.log(localStorage["pixl"],localStorage["markerLat"], localStorage["markerLon"]);
});
}
</script>
Function pixl is always undefined. I realize it's a question that have been asked many times. In fact I've tried to adapt many methods. My starting points are this: convert-lat-lon-to-pixels-and-back and of course this: showing pixel and tile coordinates. I can't spot the problem.
Please note that the fromLatLngToPoint method requires a google.maps.LatLng class as its parameter. From the documentation:
fromLatLngToPoint(latLng[, point])
Parameters:
latLng: LatLng
point: Point optional
Return Value: Point optional
Translates from the LatLng cylinder to the Point plane. This interface specifies a function which implements translation from given LatLng values to world coordinates on the map projection. The Maps API calls this method when it needs to plot locations on screen. Projection objects must implement this method, but may return null if the projection cannot calculate the Point.
So in your code, I would do it this way instead:
var worldPoint = projection.fromLatLngToPoint(marker.getPosition());
Another thing I (and #geocodezip) noticed is that you are not passing a parameter to your pixl function. This is why it is intended for you to get an undefined response. You should include a parameter like below instead in order to get the correct value:
localStorage["pixl"] = JSON.stringify(pixl((markerposLat,markerposLon)));
Here is the working fiddle for this.
I have a Google Maps script in this format:
function initMap()
{
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(mapDiv, {center: {lat: 45.9, lng: 25.0}, zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP, disableDoubleClickZoom:true, scrollwheel:false, ...});
var marker = new google.maps.Marker({position: {lat:46.1, lng:25.4}, map:map, icon:'../images/Marker.png});
}
I'd like to know how the var marker part of the script must look like if there were more than one points to be displayed. Note: I have seen JavaScript examples on StackExchange which use arrays etc. - one of the best is here: Google Maps Script - but I want my script to use the format above, which is very simple.
The google.maps.Marker class can only create a marker for a single point at at time, so you'll need some way to repeat that for all your points.
I'd say have an array of objects, each of which has the latitude and longitude values as separate properties. And any other properties you might want to associate with all your points, such as titles and icons. e.g.
var places = [
{
latitude: 46.1,
longitude: 25.4
title: "Place 1",
icon: "blue.png"
},
{
latitude: 54.1,
longitude: 0.0
title: "Place 2"
icon: "red.png"
},
// etc
];
Then when you want to create the markers, just loop over the array:
for (var i = 0; i < places.length; i++) {
marker = new google.maps.Marker({
position: {lat:places[i].latitude, lng: places[i].longitude},
title: places[i].title,
map: map,
icon: '../images/' + places[i].icon
});
}
I have 2 routes, routes A to B and C to D on google maps. Now route C to D share the same street/path with route A to B. How do I check if one is on the polyline of the other?
For example: C to D is on A to B
You can use Geometry Library's poly namespace which contains utility functions that determine whether a given point is inside or near a polygon or polyline.
Use isLocationOnEdge(point:LatLng, poly:Polygon|Polyline, tolerance?:number) method to determine whether a point falls on or near a polyline, or on or near the edge of a polygon. You need to pass the point, the polyline/polygon, and optionally a tolerance value in degrees to google.maps.geometry.poly.isLocationOnEdge() then the function returns true if the distance between the point and the closest point on the line or edge falls within the specified tolerance.
Example:
function initialize() {
var myPosition = new google.maps.LatLng(46.0, -125.9);
var mapOptions = {
zoom: 5,
center: myPosition,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map'),
mapOptions);
var cascadiaFault = new google.maps.Polyline({
path: [
new google.maps.LatLng(49.95, -128.1),
new google.maps.LatLng(46.26, -126.3),
new google.maps.LatLng(40.3, -125.4)
]
});
cascadiaFault.setMap(map);
if (google.maps.geometry.poly.isLocationOnEdge(myPosition, cascadiaFault, 10e-1)) {
alert("Relocate!");
}
}
google.maps.event.addDomListener(window, 'load', initialize);
You can also check these examples on GitHub.
I have the following code:
google.maps.event.addListener(map, 'idle', function() {
var request = {
bounds: map.getBounds(),
keyword: selected_provider //some value
};
service.radarSearch(request, function(results, status) {
for (var i = 0; i < results.length; i++) {
var marker = new google.maps.Marker({
position: results[i].geometry.location,
map: map
});
});
});
});
in some cases, results' array has some locations that which markers are printed outside the map bounds.
map.getBounds() return this:
oh {Da: mh, va: hh}
Da: A: -23.53883129305287 j: -23.53223111409202
va: A: -46.6811610542145 j: -46.686782964309714
A certain result:
A: -23.536062
F: -46.68732699999998
So, F (the longitude) is not inside the longitudes from southWest and NorthEast.
Anyone have ever seen this?
As explained here
https://code.google.com/p/gmaps-api-issues/issues/detail?id=8340
"Bounds used to bias results when searching for Places (optional). Both location and radius will be ignored if bounds is set. Results will not be restricted to those inside these bounds; but, results inside it will rank higher."
It doesn't make any sense for me to perform a search with bounds as parameters and the response comes with results outside the bounds. The only thing I think I can do is iterate the results array before showing them, and check if each item is inside bounds.
I'm writing some Google Maps API v3 code, which seems to work just fine with multiple markers, but when there's only 1, it always plots the marker in the top left of the map, just beyond the visible area:
Here's my coffeescript code:
class SimpleMap
constructor: (div_id, lat = 40.783627, lng = -73.942583) ->
# L.Icon.Default.imagePath = "/assets"
#div_id = div_id
#map_options = {center: new google.maps.LatLng(lat, lng), zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP}
#markers = []
#map = new google.maps.Map document.getElementById(div_id), #map_options
#loadMarkers() # gets them and plots on the map
#autoFit()
loadMarkers: ->
items = $(".grid-item[data-lat], .apartment[data-lat]")
for item in items
console.log "Adding #{item}"
#addMarker(item)
#autoFit()
addMarker: (item) ->
console.log "Adding marker"
lat = $(item).attr("data-lat")
lng = $(item).attr("data-lng")
console.log "#{lat}, #{lng}"
marker = new google.maps.Marker(
position: new google.maps.LatLng lat, lng
map: #map
title: "This is my marker"
)
#markers.push marker
autoFit: ->
bounds = new google.maps.LatLngBounds()
for marker in #markers
bounds.extend marker.getPosition()
#map.fitBounds bounds
# if you leave out the below, the marker appears int he same position as in the screenshot (slightly off screen) but at the max zoom level.
listener = google.maps.event.addListener(#map, "idle", =>
#map.setZoom 9 if #map.getZoom() > 8
#map.setCenter #markers[0].getPosition()
google.maps.event.removeListener listener
)
The map seems to ignore my attempts to set setCenter(#markers[0].getPosition()). Any ideas?
I believe the issue is in:
bounds = new google.maps.LatLngBounds()
for marker in #markers
bounds.extend marker.getPosition()
#map.fitBounds bounds
where you are extending the current map bounds to include all markers, but you have only one marker, the bounds will extend in a way that the marker will be in the map limit border.
Regards
Following the comments this issue occurs only when there is 1 marker.
Based on this fact I would neardown the problem to this line:
#map.fitBounds bounds
When there is only 1 marker, the NE-corner of bounds is equal to the SW-corner.
I noticed unexpected interactions when you use bounds as fitBounds()-argument in this case.
Suggestion:
only use fitBounds() when there are at least 2 markers.