LatLngBounds more than 2 parameters [duplicate] - javascript

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]);
}

Related

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

I have a polygon , and I know all of 4 points. How do I determine if a given point is inside the polygon with OpenLayers?

I referred this post
How to determine if a point is inside a 2D convex polygon?
But I want to do the same in OSM with Open Layers.Please help me.
[Link](http://jsfiddle.net/Sanju5390/3tpLs6w3/)
You can do this with turf.js using turf.inside:
var polygon = new ol.Feature(new ol.geom.Polygon([[[-5e6, -1e6], [-4e6, 1e6],
[-3e6, -1e6], [-5e6, -1e6]]]));
var point = new ol.Feature(new ol.geom.Point([-4e6, 0e6]));
var format = new ol.format.GeoJSON();
var isInside = turf.inside(
format.writeFeatureObject(point),
format.writeFeatureObject(polygon));
console.log(isInside);
http://jsfiddle.net/d6o81vc7/22/

Google maps setPaths from getPaths coordinates

I'm trying to get the Paths of a polygon, and then set them to another polygon like that.
newpoly = new google.maps.Polygon({
paths:poly.getPaths()
});
Isn't this suppose to work ? It gives me this error in the console.
Invalid value for constructor parameter 0: [object Object]
Try adding the following before you instantiate the polygon object
var triangleCoords = [
new google.maps.LatLng(25.774252, -80.190262),
new google.maps.LatLng(18.466465, -66.118292),
new google.maps.LatLng(32.321384, -64.75737),
new google.maps.LatLng(25.774252, -80.190262)
];
Now use you code and replace the poly.getPaths() - Assuming the rest of your code works.
newpoly = new google.maps.Polygon({
paths:triangleCoords //there are probably more method to add here
});
If it works then you know there is something wrong with poly.getPaths(). Use this as reference https://developers.google.com/maps/documentation/javascript/overlays#PolygonOptions.
Remember that we can only use the code that was provide to formulate an solution.
It would help if you can show the code for poly object and if poly.getPaths() return anything. All I can recomand si to debug it in detail like this:
Do you hace any error if you comment paths:poly:Paths();
Console.log(poly); return a google map polygon?
Console.log(poly.getPaths()) return an array of paths?
If yes, you can try to create an array from poly.getPaths then pass it to newpoly.
Get the coords of first polygon this way (assuming that the two polygons were already created):
//store polygon path
var vertices = firstPolygon.getPath();
// Iterate over the vertices.
pathOfFirstPolygon = [];
for (var i =0; i < vertices.getLength(); i++) {
var xy = vertices.getAt(i);
item = {};
item["lat"] = xy.lat();
item["lng"] = xy.lng();
pathOfFirstPolygon.push(item);
};
//Set path of the second polygon
secondPolygon.setPath(pathOfFirstPolygon);

Openlayers OSM always set on (long/lat) (0/0)

this is my code
map = new OpenLayers.Map("map");
// I tried several projections here, all lead to the same result
var proj = new OpenLayers.Projection("WGS84");
var point = new OpenLayers.LonLat(position.coords.latitude,position.coords.longitude);
point.transform(proj, map.getProjectionObject());
// the output of this shows the correct coordinates
console.log("latitude: "+position.coords.latitude+" long "+position.coords.longitude);
var mapnik = new OpenLayers.Layer.OSM();
map.addLayer(mapnik);
map.setCenter(point,3);
It always shows the map centered on coordinate (0/0) which is somewhere in the Atlantic Ocean. Where is my error? I cant solve this and find nothing on Google.
This, however, works.
map = new OpenLayers.Map( 'map');
layer = new OpenLayers.Layer.OSM( "Simple OSM Map");
map.addLayer(layer);
map.setCenter(
new OpenLayers.LonLat(position.coords.latitude,position.coords.longitude).transform(
new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject()
), 12
);
If you tried several projections and all lead to the same result that's probably because Proj4js is not correctly loaded (see http://trac.osgeo.org/openlayers/wiki/Documentation/Dev/proj4js)
Check also this example: http://openlayers.org/dev/examples/osm.html (coords re-projection from EPSG:4326)

Google Maps v3 - Why is LatLngBounds.contains returning false

I have the following code in which I would expect the contains method to return true, but it returns false:
var bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(55.38942944437183, -2.7379201682812226),
new google.maps.LatLng(54.69726685890506, -1.2456105979687226)
);
var center = bounds.getCenter(); // (55.04334815163844, -1.9917653831249726)
var x = bounds.contains(center); // returns false
On the same page, where map is a reference to the Map object, the following code returns true as expected:
map.getBounds().contains(map.getBounds().getCenter())
Why might my call to bounds.contains be returning false?
Ah, brilliant. The google.maps.LatLngBounds constructor expects SouthWest and NorthEast LatLng parameters. I have somehow bungled up my coordinates and passed in NorthWest and SouthEast instead!
var bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(54.69726685890506,-2.7379201682812226),
new google.maps.LatLng(55.38942944437183, -1.2456105979687226)
);
var center = bounds.getCenter(); // still returns (55.04334815163844, -1.9917653831249726)
var x = bounds.contains(center); // now returns true
Lesson learned: getCenter doesn't care if you created the LatLngBounds with NorthWest and SouthEast instead, but if you want contains to return a useful answer you better pass in the suggested SouthWest and NorthEast!
I guess its easier to try this. It works for me without having to worry about NE orSW
var bounds = new google.maps.LatLngBounds();
bounds.extend(54.69726685890506,-2.7379201682812226);
bounds.extend(55.38942944437183, -1.2456105979687226);
var center = bounds.getCenter(); // still returns (55.04334815163844, -1.9917653831249726)
var x = bounds.contains(center); // now returns true
I know this post is old, but I came searching for answers here, so thought of updating from what I have learnt.
This is the way that it worked for me:
var bounds = new google.maps.LatLngBounds();
bounds.extend(54.69726685890506,-2.7379201682812226);
bounds.extend(55.38942944437183, -1.2456105979687226);
map.fitBounds(bounds);

Categories

Resources