Functions for Object Literals Google Maps API - javascript

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)

Related

how to obtain marker's pixel coordinates

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.

Google Maps - how to set the zoom level [duplicate]

This question already has answers here:
How to set zoom level in google map
(6 answers)
Closed 6 years ago.
I have been trying for 4+ years to figure out how to use google maps. Im beyond ecstatic to have finally become able to generate a map wiht the correct address.
This is my javascript.
I'm now struggling with how to set the zoom level. I've tried it in each of the places I've shown below - but none of them work. In each case (regardless of the number I set as the zoom level) I get a really close up map of the specific building.
Can anyone see what I'm doing wrong, or what I need to do in order to get my map to recognise my request for a zoom level? I don't get any js errors showing in the console.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5
});
var bounds = new google.maps.LatLngBounds();
// var opts = {
// zoom: 10,
// max_zoom: 16
// }
var n = addresses.length;
for (var i = 0; i < n; i++) {
var lat = addresses[i].latitude;
var lng = addresses[i].longitude;
if (lat == null || lng ==null){
console.log(addresses[i].name + " doesn't have coordinates");
}else {
var address = new google.maps.Marker({
position: {lat: parseFloat(lat), lng: parseFloat(lng)},
title: addresses[i].name,
map: map //,
// zoom: 8
});
bounds.extend(address.position);
}
}
map.fitBounds(bounds);
}
Note in response to why this question is different to many others asked on SO. I am specifically struggling with how and where to use the features provided in this JS. I can't understand any of the JS I have managed to generate - the version above is the result of 4+ years of effort in trying to learn. I can't take generic ideas in other posts and apply them as easily as others may be capable of doing. Please bear with me as I try to learn to decipher how to communicate with these languages. It's not something that I've been able to grasp readily.
Also, and specifically to the point in the answer you have flagged - maybe the code was good at the point in time the question was asked, but it looks from the google library that the correct expression should be "zoom:4" not setZoom(something). I tried both and can't get either of them to work in my code.
XOMENA'S SUGGESTION
Taking Xomena's suggestion, I tried to define zoom and center in my map function (although I'm not suer if I've done this in the correct place).
This doesnt work. The console shows an error with my js file that says:
Uncaught SyntaxError: Unexpected identifier
Now, my js file has:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
setZoom: 5
setCenter = addresses.first
});
var bounds = new google.maps.LatLngBounds();
// var opts = {
// zoom: 10,
// max_zoom: 16
// }
var n = addresses.length;
for (var i = 0; i < n; i++) {
var lat = addresses[i].latitude;
var lng = addresses[i].longitude;
if (lat == null || lng ==null){
console.log(addresses[i].name + " doesn't have coordinates");
}else {
var address = new google.maps.Marker({
position: {lat: parseFloat(lat), lng: parseFloat(lng)},
title: addresses[i].name,
map: map //,
// zoom: 8
});
// bounds.extend(address.position);
}
}
// map.fitBounds(bounds);
}
I can't find an example of how to set this up to work. I've tried putting the set zoom and set centre lines in each block of text in this js file, but I can't find a formulation that works.
NEXT ATTEMPT
I tried moving my application javascript include tag out of the head tag and beneath the body tags on my application.html.erb.
Now, I have an error that says:
js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:95 Uncaught Eb {message: "initMap is not a function", name: "InvalidValueError", stack: "Error↵ at new Eb (https://maps.googleapis.com/m…3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:130:73"}message: "initMap is not a function"name: "InvalidValueError"stack: "Error↵ at new Eb (https://maps.googleapis.com/maps/api/js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:41:365)↵ at Object._.Fb (https://maps.googleapis.com/maps/api/js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:41:475)↵ at Lg (https://maps.googleapis.com/maps/api/js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:95:420)↵ at https://maps.googleapis.com/maps/api/js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:130:58↵ at Object.google.maps.Load (https://maps.googleapis.com/maps/api/js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:21:5)↵ at https://maps.googleapis.com/maps/api/js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:129:20↵ at https://maps.googleapis.com/maps/api/js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:130:73"__proto__: ErrorLg # js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:95(anonymous function) # js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:130google.maps.Load # js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:21(anonymous function) # js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:129(anonymous function) # js?key=AIzaSyAleQgfNH3HRQVUCYnyAzp46xmXW7WrWrc&callback=initMap:130
kwift.CHROME.min.js:1271 Uncaught SyntaxError: Identifier 'findGoodContent' has already been declared
I have seen SO posts form others using angular (i don't use that) which suggest adding another js file to the view where the map is displayed.
Can anyone help solve this for rails where angular is not used?
The map.fitBounds() method adjusts the zoom level automatically to show all locations that you added into LatLngBounds. If you want to set zoom level yourself, don't use map.fitBounds() and use map.setZoom() method instead.
https://developers.google.com/maps/documentation/javascript/reference#Map

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.

Google Maps API Polyline creation failing with "Uncaught TypeError: number is not a function"

I'm working a django project using the google maps JS api.
Basically what's going on here is that I'm creating a map centered at a point (works perfectly), drawing a bunch of points specified by the journey variable (value is substituted in by django template),
and then trying to draw a polyine between these points. (Fails to produce a polyline with a "Uncaught TypeError: number is not a function" at the JS console.)
The traceback at the JS console is pretty indecipherable to me, particularly due to all the .js files being minned.
When I log the path attribute of the polyline, and the coordinate I'm adding (as seen below), everything seems to work. I know the coord is formatted correctly, because I think Marker and Polyline should take the same datatype (LatLng) for their locations, and the Markers work fine. Anyone have any idea what's happening?
var mapOptions = {
center: { lat: 37.23112,
lng: -122.29398
},
zoom: 15
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Make the line that will trace the guys route:
var polyOptions = {
strokeColor: '#000000',
srokeOpacity: 1.0,
strokeWeight: 3
};
var poly = new google.maps.Polyline(polyOptions);
poly.setMap(map);
// Make an array of everywhere the lilguys has been. Passed into this django template as {"lat": 12, "lng": 8} objects.
var journey = [{"lat": 33.2389, "lng":-123.9349}, {"lat":32.928392, "lng":-122.29289}, {"lat":33.928982, "lng":-120.298392}];
var journey_markers = [];
// Draw all the placemarks
for (var i = 0; i < journey.length; i++) {
var coord = journey[i];
journey_markers.push(new google.maps.Marker({position: coord, map:map}));
var path = poly.getPath();
console.log(coord);
console.log(path);
path.push(coord);
}
Thank you!
EDIT:
I substituted the template variables in for what they evaluate to. This was checked by looking at the HTML source code in the browser, and confirmed to not be the source of the bug.
Figured out the answer. It seems to be that unlike Markers, the Polyine path requires google.maps.LatLng() objects rather than latlng literals.
The following fixes the issue:
...
// Draw all the placemarks
for (var i = 0; i < journey.length; i++) {
var coord = new google.maps.LatLng(journey[i].lat, journey[i].lng);
...

Dynamic Google map zoom getBounds() undefined

I have this piece of javascript code
var myOptions = {
zoom:9,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var latlongcollection = new Array();
// some more code to push latlng objects into latlongcollection
map.setCenter(latlongcollection[0]);
for(latlong in latlongcollection){
map.getBounds().extend(latlong);
}
map.fitBounds(map.getBounds());
But everytime its giving me error map.getBounds() is undefined. center is set and even. zoom is set before I call map.getBounds(). Please help
Try using a new google.maps.LatLngBounds object instead of map.getBounds():
var bounds = new google.maps.LatLngBounds()
// note: this for/in loop is erronous
//for(latlong in latlongcollection){
// bounds.extend(latlong);
//}
for ( var i = 0,len=latlongcollection.length;i<len;i++) {
bounds.extend( latlongcollection[ i ] );
}
map.fitBounds( bounds );
Also, the for loop you use is bad in conjunction with arrays. A for/in on an array will loop not only over indexed values, but also properties and methods. So you will be extending you bounds with .length and .push and so on. This alone might've also caused the bug. Always read for/in loops as:
for property in object
Which includes methods and so on.

Categories

Resources