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
Related
At the moment I'm working on a project in which I'm supposed to show various customers worldwide on a map. I determine the coordinates of these customers using the Bing Maps API. But if I then want to display these customers on the map, I get the error for some that the coordinates are wrong. The coordinates in the database look correct and are returned to me by the Bing Maps API.
Now to the question:
How do I catch this error so that the script doesn't crash because of it?
let map;
let searchManager;
let customers = <?= json_encode($elements); ?>;
let pins = [];
let iconURL = '';
function GetMap() {
var statusDropdownValue = parseInt($('#status').val());
map = new Microsoft.Maps.Map('#map', {
zoom: 1
});
$.each(customers, function(index, value) {
var customerLocation = new Microsoft.Maps.Location(value['latitude'], value['longitude']);
var pin = new Microsoft.Maps.Pushpin(customerLocation, {
icon: baseURL + 'assets/images/pin.png'
});
pin.metadata = {
id: value['id'],
customerName: value['customer_name'],
postCode: value['post_code'],
city: value['city'],
countryCode: value['country_code']
};
pins.push(pin);
});
Microsoft.Maps.loadModule("Microsoft.Maps.Clustering", function () {
clusterLayer = new Microsoft.Maps.ClusterLayer(pins);
map.layers.insert(clusterLayer);
});
Microsoft.Maps.loadModule('Microsoft.Maps.AutoSuggest', function () {
var manager = new Microsoft.Maps.AutosuggestManager({ map: map });
manager.attachAutosuggest('#search', '#search-container-search-bar', selectedSuggestion);
});
}
Error:
Uncaught Error: Invalid latitude
n https://r.bing.com/rp/iKR9c24bDSIz79-enVSnBoJvZx8.br.js:1
GetMap http://localhost/projects/BattermannTillery_HK_Locator/maps:101
each jQuery
GetMap http://localhost/projects/BattermannTillery_HK_Locator/maps:100
notifyMapReadyForBootstrap https://www.bing.com/api/maps/mapcontrol?callback=GetMap&setMkt=en-US&setLang=en&key=AlV57vXOvuSENqgwu6hnNKGhiLf85dbTMlnDY81z2cGq40L1xkMdXUVSkEhvqfvv:12
<anonymous> https://r.bing.com/rp/RENSVX2edu6CiHiu-aMi-GbtqbA.br.js:1
<anonymous> https://r.bing.com/rp/RENSVX2edu6CiHiu-aMi-GbtqbA.br.js:1
I would do the following to debug this issue:
Open dev console in browser, add a break point where you create the Location object. Check to see if value['latitude'] is a string number or an actual number ("1" vs 1). If it is a string, wrap value['latitude'], value['longitude'] with parseFloat like (parseFloat(value['latitude']). This is the most common cause of this type of error.
If the above doesn't solve your issue, it would be best to check your data (I'm assuming you have the coordinates stored somewhere). Double check you haven't reversed latitude and longitude values (take a couple of entries and manually search for them on bing.com/maps and check the coordinates to verify what you have in your lat/lon columns is in the same general area). If you can query your dataset (is it a database?), you can check all latitude and longitude values. Latitude values should be between -90 and 90 degrees, and longitude between -180 and 180. If you find anything outside of this range it will be either due to bad data, or you have latitude/longitude values swapped in your data.
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)
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);
...
This question already has answers here:
How to use containsLocation in Google maps geometry library.
(2 answers)
Closed 8 years ago.
in my javascript code, i have code like this :
var myLocation = new google.maps.LatLng(52.585701,20.453212);
var allowBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(52.584903,20.451171),
new google.maps.LatLng(52.589701,20.463865)
);
if (allowBounds.contains(myLocation))
console.log('allowed');
else
console.log('disallowed');
it's work, the result is 'allowed', because i just use 2 parameter for allowBounds (southWest and northEast point).
now i have kml file with polygon coordinats more than 2 coordinat. i want use those coordinats for allowBounds paramater. because i want to check whether myLocation coordinat is in polygon location/area or not. mybe like this :
var allowBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(52.584903,20.451171),
new google.maps.LatLng(52.589701,20.463865),
new google.maps.LatLng(52.629701,20.413865),
new google.maps.LatLng(52.572190,20.963865)
);
that is possible?? if not, can you give me some advice to check myLocation coordinat is in polygon area or not without use google.maps.LatLngBounds??
thank you for your helped.
According to the documentation you can't put more than 2 coordinates in the constructor. However, you can add more than 2 coordinates to a LatLngBounds object by using the .extend(point:LatLng) function.
var markers = [
new google.maps.LatLng(1.234, 5.678),
new google.maps.LatLng(1.234, 5.678),
new google.maps.LatLng(1.234, 5.678)
];
var bounds = new google.maps.LatLngBounds();
for (index in markers) {
bounds.extend(markers[index]);
}
Edit:
Question = "is there a way to loop through the array and check if each location (long/lat) falls within the current viewport directly" (failing that get all markers within the viewport)
Background:
I have an array of locations (lat, long, id).
I want to:
On a Google Map, use the location array to display markers.
The user can scroll/zoom the map.
Have a button underneath the map, so when the user has decided on an area, he can click the button, and the code will return the ids (from the location array) that are contained within the viewport / map bounds.
There is a .contains for Google, so I guess you could potentially use that with something like
map.getBounds().contains and somehow reference each marker.getPosition()
but I wonder if there's a way to loop through the array and check if each location (long/lat) falls within the current viewport directly
You mean something like this (not tested), map is the google.maps.Map object and needs to be in scope. markersArray is the array of markers.
for (var i=0; i< markersArray.length; i++) {
if (map.getBounds().contains(markersArray[i].getPosition())) {
// the marker is in view
} else {
// the marker is not in view
}
}
http://jsfiddle.net/UA2g2/1/
Thanks geocodezip, you gave me the idea on how to solve it via looping through the array. I don't know if this is the most efficient way, but I put together some code that seems to do what I want - if you check the jsfiddle above and view console you can see that it logs when and which points are in the viewport.
$(document).ready(function(){
var myOptions = {
center: new google.maps.LatLng(51, -2),
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var storeArray = new Array(["51.38254", "-2.362804", "ID1"], ["51.235249", "-2.297804","ID2"], ["51.086126", "-2.910767","ID3"]);
google.maps.event.addListener(map, 'idle', function() {
for (i = 0; i < storeArray.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(storeArray[i][0], storeArray[i][1]),
map: map
});
}
for (var i=0; i<storeArray.length; i++) {
if (map.getBounds().contains(new google.maps.LatLng(storeArray[i][0], storeArray[i][1]))) {
console.log("marker: " + storeArray[i][2]);
}
}
});
});