Google Marker does not appear with user defined points - javascript

just wondering if anyone would be able to tell me how to solve an issue that I've been running into? The user puts in coordinates (ex: 85.231,40.213) into a text area, which populate and array, splits them, and then attempts to create a marker where the user specified.
var stringArray = document.getElementById("geos").value.split('\n');
var x = [];
var y = [];
var cords = [];
var array = stringArray.split(','); //splits up array by ","
var j = 0;
for (var i = 0; i < array.length; i++) //assigns broken up array into x and y values
{
x[j] = array[i];
i++;
y[j] = array[i];
j++;
}
var textarea = document.getElementById("test");
//textarea.value = stringArray.join("\n");
//textarea.value = y;
for (var i = 0; i < stringArray.length; i++) //assigns x and y variables to coordinates
{
cords[i] = new google.maps.LatLng(x[i],y[i]);
}
textarea.value = cords.join("\n");
for ( var i = 0; i < cords.length; i++ ) //code that plots all the points in the array
{
var marker = new google.maps.Marker({ //create a new marker
position: cords[i],
map: map,
})
map.addOverlay( marker );
}
When I add ".toString()" in between "stringArray" and "split(",")" I'm able to output the items to another text area, however it seems that the information does not want to display. Any insights?
Thanks

map: map,
that last comma will cause a syntax error, remove it.

What you probably need to do is make sure that your latlng coordinates are correctly converted from strings to numbers. e.g. this might help, changing this line:
cords[i] = new google.maps.LatLng(x[i],y[i]);
to this:
cords[i] = new google.maps.LatLng(parseFloat(x[i]), parseFloat(y[i]));

Related

Highlighting areas in leaflet using markers?

I'm trying to highlight an area surrounded by node markers. Currently, I'm doing this by creating polygons. Each node in the database is assigned a polygon ID and those with the same IDs are pushed into the array to act as the vertices of the same polygon.
However, as the data is retrieved from the database in the order they were entered into the table, polygon self-intersection happens like in the picture below:
Self-intersection in polygon
I've tried to sort the vertices by starting from the first and looking for the nearest node, then from that node I look for the nearest again and so on. It worked for some, but some cases still have self-intersection like this:
Self-intersection after sorting using nearest node
Is there any leaflet plugin that will allow me to highlight an area surrounded by nodes? Below is my code for sorting the vertices. All vertices of the same polygon ID are first pushed into the array "arr" before being sorted.
var i;
var j;
var flag = 0;
var sortedarray = [];
var finalarray = [];
for (j = 0; j < initiallength - 1; j++) {
if (flag == 0) {
finalarray.push(arr[0]);
arr.splice(0, 1);
flag++;
}
sortedarray = [];
for (i = 0; i < arr.length; i++) {
var x = L.GeometryUtil.distance(map, finalarray[j], arr[i]);
sortedarray.push(x);
}
var smallest = Math.min.apply(Math, sortedarray);
var x = sortedarray.indexOf(smallest);
finalarray.push(arr[x]);
arr.splice(x, 1);
}
var polygon = L.polygon(finalarray).setStyle(myStyle).addTo(map);

Google Maps listener does not work in `d3.csv()`

I'm trying to build a map in Google Maps Javascript API that uses D3.js to read in data. When a user clicks a circle, console.log() should display information from that datapoint.
function initMap(){
var mapObj = {};
$.getJSON("data/Base GMap style.json",function(GMapBaseStyle){
var map = new google.maps.Map("map-element", {mapTypeId: google.maps.MapTypeId.ROADMAP});
d3.csv("data.csv").then(function(data){
for (var i = data.length - 1; i >= 0; i--) {
var d = data[i];
var circle = new google.maps.Circle({
center: {
d["lat"],
d["lon"]
}
});
circle.addListener("click",function(event){
console.log(d)
})
}
}
})
}
The circles appear in the correct coordinates but when I click each one, console.log() prints d for the last element of data in the for loop.
How do I set this up so that console.log() prints the correct d?
I changed
var d = data[i];
to this:
let d = data[i];

PaperJs Add 2 raster as 2 symbols in the same project

I have this project in paperjs:
var url = "http://www.clker.com/cliparts/q/I/s/P/E/3/yellow-umbrella-md.png";
raster = new Raster(url);
raster.rotate(10);
raster.scale(0.4);
var url2 = "https://images.vexels.com/media/users/3/145373/isolated/preview/98721f602aa3fadb040e0a161ab3f966-waterdrop-vislumbrante-vis-o-ilustra--o-by-vexels.png";
secondRaster = new Raster(url);
secondRaster.scale(0.9);
var count = 150;
var symbol = new Symbol(raster);
var secondSymbol = new Symbol(secondRaster);
for (var i = 0; i < count; i++) {
// The center position is a random point in the view:
var center = Point.random() * view.size;
var placedSymbol = symbol.place(center);
placedSymbol.scale(i / count);
}
function onFrame(event) {
// Run through the active layer's children list and change
// the position of the placed symbols:
for (var i = 0; i < count; i++) {
var item = project.activeLayer.children[i];
// Move the item 1/20th of its width to the right. This way
// larger circles move faster than smaller circles:
item.position.y += item.bounds.width / 80;
// If the item has left the view on the right, move it back
// to the left:
if (item.bounds.bottom > view.size.width) {
item.position.y = -item.bounds.width;
}
}
}
The first raster has a symbol works good, but the second can't make it work... I read about to add more than one symbol to project.activeLayer.children but don't work. Even if I do a group of an array with both symbols also don't show up.
I read in a post that symbols can't be added as a group. Being that be true, it should be ok to be added even though isolated...
Anybody had done something similar?
Thank you
There are some mistakes in your code:
The most important one, that make you think that the second raster doesn't work, is that you are creating the second raster with the variable url instead of url2. So both rasters use the same image as source...
You need to place the second symbol like you do with the first one otherwise it will never get rendered.
When iterating through active layer children, make sure to iterate over all children by using project.activeLayer.children.length (as you are placing count * 2 symbols).
When checking for bottom reaching items, use height instead of width.
Here is a sketch demonstrating the solution.
var COUNT = 10;
var raster = new Raster('http://www.clker.com/cliparts/q/I/s/P/E/3/yellow-umbrella-md.png');
raster.rotate(10);
raster.scale(0.4);
var secondRaster = new Raster('https://images.vexels.com/media/users/3/145373/isolated/preview/98721f602aa3fadb040e0a161ab3f966-waterdrop-vislumbrante-vis-o-ilustra--o-by-vexels.png');
secondRaster.scale(0.15);
var symbol = new Symbol(raster);
var secondSymbol = new Symbol(secondRaster);
for (var i = 1; i <= COUNT; i++) {
// first symbol
symbol.place(Point.random() * view.size).scale(i / COUNT);
// second symbol
secondSymbol.place(Point.random() * view.size).scale(i / COUNT);
}
function onFrame(event) {
for (var i = 0; i < project.activeLayer.children.length; i++) {
var item = project.activeLayer.children[i];
item.position.y += item.bounds.height / 80;
if (item.bounds.bottom > view.size.height) {
item.position.y = -item.bounds.height;
}
}
}

Finding if a point is in a polygon

I have this code here that is attempting to work out if a point latLng passes through a polygon Maps.area.
Maps.ui.contains = function(latLng){
//poly.getBounds gets the 'box' around the polygon
if(!Maps.ui.getBounds().contains(latLng))
return false;
//So we dont need to check t/f, we either set it or we dont
var inPolygon = false;
var count = 0;
Maps.area.getPaths().forEach(function(el0, index0){
var last = el0.getLength() - 1;
el0.forEach(function(el1, index1){
count += Maps.ui.ray_intersect_segment(latLng, el1, el0.getAt(last));
last = index1;
});
});
if(Maps.area.getPaths().getLength()%2 == 0)
return count%2==0;
else
return count%2!=0;
}
var eps = 0.0001;
var inf = 1e600;
Maps.ui.ray_intersect_segment = function(point, i1, i2){
var p = point;
var segment = (i1.lng() > i2.lng())?[i2, i1]:[i1, i2];
p = (p.lng() == segment[0].lng() || p.lng() == segment[1].lng())?new google.maps.LatLng(p.lng() + eps):p;
if(p.lng() < segment[0].lng() || p.lng() > segment[1].lng() || p.lat() > [segment[0].lat(), segment[1].lng()].max())
return 0;
if(p.lat() < [segment[0].lat(), segment[1].lat()].min())
return 1;
var a = (segment[0].lat() != segment[1].lat())?(segment[1].lng() - segment[0].lng())/(segment[1].lat() - segment[0].lat()):inf;
var b = (segment[0].lat() != p.lat()) ? (p.lng() - segment[0].lng())/(p.lat() - segment[0].lat()):inf;
return (b > a)?1:0;
}
Maps.ui.getBounds = function() {
//Lets make a box
var bounds = new google.maps.LatLngBounds();
//Get all the points lines of the polly
var paths = Maps.area.getPaths();
for (var p = 0; p < paths.getLength(); p++)
//To store each path
var path = paths.getAt(p);
//Now lets expand the box
for (var i = 0; i < path.getLength(); i++)
//Add each point of the line to the 'box' making it bigger each time
bounds.extend(path.getAt(i));
//Reaturn the bounds, this has a contains method so we can check if the latLng is in it.
return bounds;
}
Array.prototype.max = function() {
return Math.max.apply(null, this)
}
Array.prototype.min = function() {
return Math.min.apply(null, this)
}
But I can't seem to work it out. For a simple triangle or square it works perfectly, but when we get to something like this it doesn't work because we can't figure out whether count should be even or odd
The Google Maps API v3 spherical geometry library has the poly.contains. Takes a LatLng and a Polygon and tells you if the point is in the polygon.
containsLocation(point:LatLng, polygon:Polygon)
This is a pretty standard problem for geographical information systems. There are several "standard" algorithms for solving the problem. The link below notes a few of them and provides an example. Note that the algorithms tend to break down in edge cases, such as when the polygon spans the extreme lat/lon boundaries such as the poles and meridian.
Polygon Algorithms

Javascript: Generating object keys inside a loop and pushing an array of objects into each?

I am working on a Google Map here: http://crocdoc.ifas.ufl.edu/projects/chameleonmapdev/
I have the data for the markers set up in this format:
var nights = ['July1211', 'July1411'];
var waypoint_data = {
July1211: [
//Lat, long, j/a (juvenile/adult)
[25.429363, -80.508326, j],
[25.429332, -80.508216, j]
],
July1411: [
[25.42936, -80.51023, j],
[25.42936, -80.51036, j]
]
};
And the function that builds the points looks like this:
function buildPoints() {
//var marker_container = new Object;
for ( i = 0; i < nights.length ; i++ ) {
//Loop for each data point that night
for ( h = 0; h < waypoint_data[nights[i]].length; h++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(waypoint_data[nights[i]][h][0], waypoint_data[nights[i]][h][1]),
icon: waypoint_data[nights[i]][h][2],
shape: pointshape,
map: map
});
//Push waypoints into date-specific object key
//marker_container[nights[i]].push(marker);
}
}
}
I would like to push the markers for each date (night[i]) into a different object key so that I can hide/show a specific night's markers. I've tried doing this with the two marker_container lines I've commented out, but they just break my loop, and in Firebug, I get an error about marker_container[nights[i]] being undefined. nights[i] is a string, so I thought this syntax would work. Any hints are greatly appreciated, and I'm very open to suggestions for other, better ways to code this.
You can't use push on an Object, only on array. I think this is what you want to do:
function buildPoints() {
var marker_container = new Object();
for ( i = 0; i < nights.length ; i++ ) {
marker_container[nights[i]] = new Array();
//Loop for each data point that night
for ( h = 0; h < waypoint_data[nights[i]].length; h++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(waypoint_data[nights[i]][h][0], waypoint_data[nights[i]][h][1]),
icon: waypoint_data[nights[i]][h][2],
shape: pointshape,
map: map
});
//Push waypoints into date-specific object key
marker_container[nights[i]].push(marker);
}
}
}
simple proof of concept jsfiddle
If you know how many markers you'll have (let's say 10), set-up the marker container, making each element of the object an object itself, of length 2:
marker_container= new Object(10);
for (i=0; i<marker_container.length; i++){
marker_container[i]=new Object(2);
}
After creating your markers, add them to the marker_container:
marker_container[i][0] = nights[i];
marker_container[i][1] = marker;
When you want to display and hide a marker, do this:
//display
marker_container['nightX'].setMap(map);
//hide
marker_container['nightX'].setMap(null);

Categories

Resources