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);
Related
I have a model in javascript which has latitude and longitude value. I have to find a feature on the map by the ID of the element and update it's location and several other properties. My code looks like this:
function updateCoordinate(item) {
var features = source.getFeatures();
var featureToUpdate;
// find feature by custom property
for(var i=0; i< features.length; i++) {
if (features[i].get('ID') == item.ID) {
featureToUpdate = features[i];
break;
}
}
// get lon, lat from input item
var lon = item.Coordinate.Longitude;
var lat = item.Coordinate.Latitude;
// update geometry (not working)
featureToUpdate.set('Geometry', new ol.geom.Point(getPointFromLongLat(lon, lat)));
// update custom properties (working)
featureToUpdate.set('MapMarkerTitle', item.Title);
// ...
}
function getPointFromLongLat (long, lat) {
return ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857')
}
Am I doing something wrong? Is there a better way for this? Is there a better way to find feature by custom property?
By custom poperty I mean that the feature is getting initiated like this:
var fea = new ol.Feature({
geometry: new ol.geom.Point(getPointFromLongLat(lon, lat)),
MapMarkerTitle : 'AAA',
// ...
})
source.addFeatures([fea]);
The custom properties are getting updated but the coordinate doesn't seem to update. Will the feature be redrawn after updating position? The label is however redrawn so I think yes.
UPDATE
After some debugging I found out that, I mispelled the 'geometry' property with uppercase.
Actually:
featureToUpdate.set('geometry', new ol.geom.Point(getPointFromLongLat(lon, lat)));
does set the new position and update the location right away. I would still like to know if what I am doing is the good way or there is better. Thanks!
You can simplify it to:
function updateCoordinate(item) {
var featureToUpdate = source.getFeatureById(item.ID);
var coord = getPointFromLongLat(item.Coordinate.Longitude, item.Coordinate.Latitude);
featureToUpdate.getGeometry().setCoordinates(coord);
featureToUpdate.set('MapMarkerTitle', item.Title);
}
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]);
}
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);
I have a connection to a database(db). I am getting the lon, lat and name from the db and stroing them:
while ($row_ChartRS = mysql_fetch_array($sql1))
{
$latitude=$row_ChartRS['latitude'];
$longitude=$row_ChartRS['longitude'];
$bus_name =$row_ChartRS['short_name'];
//echo $latitude.'--'.$longitude.'<br>';
echo $bus_name;
I then create a map to display the data. The markers are working fine for all lat, lon locations. Code:
function init()
{
projLonLat = new OpenLayers.Projection("EPSG:4326"); // WGS 1984
projMercator = new OpenLayers.Projection("EPSG:900913"); // Spherical Mercator
overviewMap = new OpenLayers.Control.OverviewMap();
//adding scale ruler
scale = new OpenLayers.Control.ScaleLine();
scale.geodesic = true; // get the scale projection right, at least on small
map = new OpenLayers.Map('demoMap',
{ controls: [ new OpenLayers.Control.Navigation(), // direct panning via mouse drag
new OpenLayers.Control.Attribution(), // attribution text
new OpenLayers.Control.MousePosition(), // where am i?
new OpenLayers.Control.LayerSwitcher(), // switch between layers
new OpenLayers.Control.PanZoomBar(), // larger navigation control
scale,
overviewMap // overview map
]
}
);
map.addLayer(new OpenLayers.Layer.OSM.Mapnik("Mapnik"));
map.addLayer(new OpenLayers.Layer.OSM.Osmarender("Osmarender"));
//Create an explicit OverviewMap object and maximize its size after adding it to the map so that it shows
//as activated by default.
overviewMap.maximizeControl();
//Adding a marker
markers = new OpenLayers.Layer.Markers("Vehicles");
map.addLayer(markers);
vectorLayer = new OpenLayers.Layer.Vector('Routes');
map.addLayer(vectorLayer);
for (k in Locations)
{
//adding a popup for the marker
var feature = new OpenLayers.Feature(markers, new OpenLayers.LonLat(Locations[k].lon, Locations[k].lat).transform(projLonLat,projMercator));
//true to close the box
feature.closeBox = true;
feature.popupClass = new OpenLayers.Class(OpenLayers.Popup.AnchoredBubble,
{
//create the size of the box
'autoSize': true,
'maxSize': new OpenLayers.Size(100,100)
});
//add info into box
for (z in names)
{
feature.data.popup = new OpenLayers.Feature(new OpenLayers.LonLat(names[z]).transform(projLonLat,projMercator));
}
//puts a scroll button on box to scroll down to txt
//feature.data.overflow = "auto";
marker = feature.createMarker();
marker.display(true);
markerClick = function (evt) {
if (this.popup == null) {
this.popup = this.createPopup(this.closeBox);
map.addPopup(this.popup);
this.popup.show();
} else {
this.popup.toggle();
}
currentPopup = this.popup;
OpenLayers.Event.stop(evt);
};
marker.events.register("mousedown", feature, markerClick);
markers.addMarker(marker);
map.setCenter(new OpenLayers.LonLat(Locations[k].lon, Locations[k].lat).transform(projLonLat,projMercator), zoom);
var lonLat1 = new OpenLayers.LonLat(Locations[k].lon,Locations[k].lat).transform(new OpenLayers.Projection('EPSG:4326'), map.getProjectionObject());
var pos2=new OpenLayers.Geometry.Point(lonLat1.lon,lonLat1.lat);
points1.push(pos2);
//Uncomment to put boxes in when map opens
//feature.popup = feature.createPopup(feature.closeBox);
//map.addPopup(feature.popup);
//feature.popup.show()
}
var lineString = new OpenLayers.Geometry.LineString(points1);
var lineFeature = new OpenLayers.Feature.Vector(lineString,'',style_green);
vectorLayer.addFeatures([lineFeature]);
map.setCenter(lonLat1,zoom);
} //function
However the name in the popup marker is the same for all markers. i.e. the last name pulled from the db. Can anyone please help with this - I have spent 3 full days trying to fix it!
Thanks in advance!
A few comments:
The PHP code you’ve posted is completely irrelevant, since it’s not seen to be used anywhere.
The objects names and Locations aren’t declared anywhere in the code you posted. What do they contain?
In the code quoted below, you’re creating multiple new Feature objects, but you assign them all to the same property (thereby overwriting that property each time). Is that intentional?
//add info into box
for (z in names) {
feature.data.popup = new OpenLayers.Feature(new OpenLayers.LonLat(names[z]).transform(projLonLat,projMercator));
}
Edit:
This does appear to be where it’s going wrong. You should remove the for...z loop, and replace it with the following code:
//add info into box
feature.data.popup = new OpenLayers.Feature(new OpenLayers.LonLat(names[k]).transform(projLonLat,projMercator));
Since in PHP, you’re using the same index ($v) to fill both arrays, it makes sense to use the same index to read them in javascript...
Aside from that, using the for...in loop on Javascript arrays is not considered good practice, for a number of reasons. It’s better to use the following:
for (k = 0; k < Locations.length; k += 1) {
// your code
}
i had the same problem , and i solve it ...
the problem is overwrite
you don't have to loop inside your function , do the loop for function for example:
function init(z)
{
feature.data.popup = new OpenLayers.Feature(new OpenLayers.LonLat(names[z]).transform(projLonLat,projMercator));
}
for (z in names)
{
init(z)
}