how to obtain marker's pixel coordinates - javascript

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.

Related

Get lat/lng values from google map bounds

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>

How to check if 2 routes share a path

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.

Functions for Object Literals Google Maps API

I have been working on rendering a google map, using the code below: I have put it through a syntax tree ECMAScript parser and it looks to be syntactically correct about >95%.
var mapfeats = function createMap(){
options = {
zoom: 4,
center: new google.maps.LatLng( 36.73, 10 ),
mapTypeId: google.maps.MapTypeId.ROADMAP,
},
map = new google.maps.Map(
document.onmouseover.getElementById( 'map-canvas' ),
options);
var bub1 = map.Data.Point(function(map){ var vro = lat(35.0761882) + "" + lng(1.04515982)});
var bub2 = map.Data.Point(function(map){ var whr = lat(40.5569782) + "" + lng(8.56081142)});
var pup = bub1[LatLng({split("vro")[9]})] + bub2[LatLng({split("whr")[9]})]
for (pup.length[i]; i += say, say = 37; say--) {
forEach(map.Marker(function(pup){ map.getShape("oval") }) );
}};
function mapit(){
var pt = mapfeats("pup");
for( index = 0; void pt < pup.length || index++; index < pt.length) {
var coor = pup.split(9);
latlng = new google.maps.LatLng( coor[0], coor[1], coor[2], coor [3] );
marker = new google.maps.Marker( {position: latlng, map: map},{clickable: true, mapfeats, map:map});
marker.setMap( map );
}};
Now what I don't seem to understand is when I debug using the Chrome console. I have used the maps api as the source from which to debug. As I have inputted functions into the console the I encountered:
google.maps.Map({lat: 35.0761882, lng: 1.04515982})
`main.js:53 Uncaught TypeError: this[Lb] is not a function `
`at Object.Vk [as Map] (http://maps.gstatic.com/maps-api-v3/api/js/20/11b/main.js:53:915)`
Taking a look at the library, they define the aruguement wasn't evaluated bc it wasn't a function:
`var c=b||{};te(c.mapTypeId)||(c.mapTypeId="roadmap");this[Lb](c)`
therefore I was hoping to ask
(a) Are functions supposed to be defined w/in Map object literals to the extent that a compiler would check it. I am working from : JS Fiddle and have the frame that renders without map. I currently do not have the spidermonkey compiler. And would like to know why this is not compilable if it works with the ECMASCRIPT syntax tree thus the tokens should be translated into bytecode.
(b) Objective use-cases for other Map API instances that have used compiling methods in the browser. I am still quote new to the functionality of the browser dev environment.
Thanks you for yourr help .
This {lat: 35.0761882, lng: 1.04515982} is not a valid MapOptions object, it is a LatLngLiteral
google.maps.Map({lat: 35.0761882, lng: 1.04515982})
It needs to be:
google.maps.Map(document.getElementById('map-canvas'),{center:{lat: 35.0761882, lng: 1.04515982},zoom:3})
(center and zoom are required and the google.maps.Map constructor takes a DOM node as its first argument)

What do I need to do to pass value as attribute from angular template to directive?

I have a directive that looks like this:
<g-map-locations center={{myLocation}} zoom="4" id="map" class="map"></g-map-locations>
The zoom-value is used in angular to set the zoom for a google map:
attrs.zoom = zoom
setMapOptions: function(center, zoom){
var mapOptions = {
zoom: zoom,
center: center
}
return mapOptions;
},
google maps complain that setZoom: is not a number, though it works i do
zoom = 4
Can I tell angular to pass the value as a number or convert it in the directive somehow?
HTML attributes are passed in as strings, save for when they are passed in as scoped objects and parsed. The easiest solution, in my view, would be to parse the the number as integer:
setMapOptions: function(center, zoom){
var mapOptions = {
zoom: parseInt(zoom, 10),
center: center
}
return mapOptions;
}

Google Maps v3 Marker Always Appears at Top Left

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.

Categories

Resources