I currently have a set of nicely declared array of latitude/longitude points using javascript and mySQL and when I used this set of arrays to show as polylines it was successful.
var polyline= L.polyline(xxx).addTo(map);
However when I tired to change to markers, the map did not portrayed any markers.
Any help? Much appreciated :)
That's because L.Polyline, takes a nested array of multiple lat/lng coordinates as the first parameter, L.Marker takes a single array with lat/lng coordinates. The signature is different:
L.Polyline:
new L.Polyline([[-45, -45], [45, 45]], {/*options*/});
L.Marker:
new Marker([-45, -45], {/*options*/});
When you pass a nested array to L.Marker, like the one shown above in the polyline, it throws an error:
Uncaught TypeError: Cannot read property 'lat' of null
If you want to use the set of coordinates of the polyline to show markers at the start and/or endpoint of the line you could do this:
var coordinates = [[-45, -45], [45, 45]];
var startMarker = new Marker(coordinates[0], {/*options*/});
var endMarker = new Marker(coordinates[1], {/*options*/});
As promised in the comments another easier way to add markers from a large array:
var coordinates = [
[-41.31825,174.80768],
[-41.31606,174.80774],
[-41.31581,174.80777],
[-41.31115,174.80827],
[-41.30928,174.80835],
[-41.29127,174.83841],
[-41.33571,174.84846],
[-41.34268,174.82877]
];
coordinates.forEach(function (coordinate) {
new L.Marker(coordinate).addTo(map);
});
Much easier than doing:
new L.Marker(coordinate[0]).addTo(map);
new L.Marker(coordinate[1]).addTo(map);
new L.Marker(coordinate[2]).addTo(map);
new L.Marker(coordinate[3]).addTo(map);
new L.Marker(coordinate[4]).addTo(map);
new L.Marker(coordinate[5]).addTo(map);
new L.Marker(coordinate[6]).addTo(map);
new L.Marker(coordinate[7]).addTo(map);
Working example on Plunker: http://plnkr.co/edit/3dbJgb?p=preview
Related
I want to calculate the minimum distance between a point and a polyline with JavaScript and TurfJS. I can use the pointToLineDistance function for that, as follows:
var pt = turf.point([0, 0]);
var line = turf.lineString([[1, 1],[-1, 1]]);
var distance = turf.pointToLineDistance(pt, line, {units: 'miles'});
//=69.11854715938406
However, I want the LineString ('line') to be a route given by the Directions API. Therefore, I need to get the route as a set of LatLng coordinate pairs, such as:
var line = turf.lineString([
[-77.031669, 38.878605],
[-77.029609, 38.881946],
[-77.020339, 38.884084],
[-77.025661, 38.885821],
[-77.021884, 38.889563],
[-77.019824, 38.892368]
]);
The set of pairs above would form this line over Washington, DC (ignore the two markers)
How can I get a route given by the Directions API as a full set of LatLng pairs?
I tried reading through the API's documentation. You can draw polylines from routes. Assuming the polylines are drawn based on the sets of coordinate pairs of a route, they must be in there, somewhere. I just couldn't find a way to get these sets from routes.
I have a SVG based non geographical layout with image overlay.
var map = L.map('map', {
crs: L.CRS.Simple
});
var bounds = [[0,0], [1000,1000]];
var image = L.imageOverlay('uqm_map_full.png', bounds).addTo(map);
map.fitBounds(bounds);
I traced out different shapes on top of this image.
Now i want to retrieve all the shapes drawn, as a json object array and save it to database. Requirement is to replicate the same shapes later some point by fetching the json object array from database. Is it possible in leaflet.js? I want some thing like below
L.getObjectsArray(map) will give me
var leafletAllShapesConfig = [Object1,Object2,Object3,Object4,Object5]
Now reading the object array i can be able to draw the same shapes like L.draw(leafletAllShapesConfig).
Is this possible and any in built method available to achieve the same? If not please give some idea how can i achieve that.
Yes Leaflet has a built in method: L.GeoJson()
Put your shapes into a featuregroup instead to the map.
var fg = L.featureGroup().addTo(map);
L.marker(latlng,options).addTo(fg);
Then you can get the geojson from the featuregroup:
var gjson = fg.toGeoJSON()
Now you can save this geojson as string with: var str = JSON.stringify(gjson)
To add the shapes back to the map use:
var json = JSON.parse(str);
fg.clearLayers() //To clean the map from the shapes
L.geoJSON(json, {
onEachFeature: function(feature, layer) {
//Code
}
}).addTo(fg);
Now you have your shapes back on your map, but without options/properties like color. GeoJson don't convert them too. You can solve this problem by looping through the layers in the featuregroup and add them manually to the gjson and add the layer.options to the gjson.properties.options and later by adding to the map, read the options from gjson out.
After some research over leaflet.js, i figured out an event "pm:drawend" from "geoman-io/leaflet-geoman-free" plugin Github link https://github.com/geoman-io/leaflet-geoman
map.on('pm:drawend', e => {
console.log(e); //Gives array of all shapes including background image and SVG
});
Above snippet gives me an array of all shapes available(including background image and SVG container), the moment i finish adding any active shape. For reference including the output snippet here which served my purpose.
By default leaflet includes background image as first item. Then follows the SVG container(where my map resides), then all shapes.Hope this will be use to some one else.
I have a Google Map object available on my window object like so:
var map = window.site.map.el;
That Map also also has a bunch of markers placed on it, I'd like to hide a Marker on that Map where the marker's place_id property is equal to "123" for example.
However I don't see a function I can call on the Map class that will return me an array of all markers placed on the map that I can then loop through and hide depending on the marker's place_id.
Google maps does not provide a way to get all Markers, you need to do it yourself
while adding marker to the map keep it in array
var myMarkers = [];
....
for(...) {
var marker = new google.maps.Marker({...});
myMarkers.push(marker);
}
Than you can hide any marker, just by setting map to null
myMarker[i].setMap(null);
Or bring it back
myMarker[i].setMap(map);
My code is showing markers from GeoJSON, when I'm haved zoomed into zoom-level 10,it load the GeoJSON-file, but how do I avoid to reput out the same markers?
Is there a way to check if there already exist a marker on a specific place?
The code
map.events.register("zoomend", null, function(){
if(map.zoom == 10)
{
var bounds = map.getExtent();
console.log(bounds);
var ne = new OpenLayers.LonLat(bounds.right,bounds.top).transform(map.getProjectionObject(),wgs84);
var sw = new OpenLayers.LonLat(bounds.left,bounds.bottom).transform(map.getProjectionObject(),wgs84);
var vectorLayer = new OpenLayers.Layer.Vector();
map.addLayer(vectorLayer);
$.getJSON('ajax.php?a=markers&type=json&sw=('+sw.lon+','+sw.lat+')&ne=('+ne.lon+','+ne.lat+')',function(data){
//$.getJSON('test.json',function(data){
var geojson_format = new OpenLayers.Format.GeoJSON({
'externalProjection': wgs84,
'internalProjection': baseProjection
});
vectorLayer.addFeatures(geojson_format.read(data));
});
}
});
Why not use the BBOXÂ Strategy [1] ?
That will do what you need, and will for sure be more performant (it will delete existing features and reload new ones on zoomend). Comparing features to add new will need a lot of comparison, and you can end with too much features on your map.
Check out the js source of the example.
HTH,
1 - http://openlayers.org/dev/examples/strategy-bbox.html
EDIT: if you want to change less code, a call to vectorLayer.removeAllFeatures() before adding will solve your problem… Do you really need to keep features out of bound?
First you would need to get the layer off the map using something like map.getLayersByName. Then you can iterate over layer.features to look for the feature you are adding.
If you can modify the backend to use BBOX, then the BBOX strategy with zoom level and projection settings would take care of a lot for you.
I'm new to javascript and to programming itself, I'm trying to add markers in google maps api and load it's coords from mysql, I have everything done but now I got stuck into something, is it possible to create a number of variables based on the number of coords I have ? here is what I have:
function get_values(numero, array)
{
var i;
for(i=0;i<numero;i++)
{
//var i ( HERE: i want it to set variables based on i )= new google.maps.Marker({
position: array[2],
//map: map,
//title:"Hello World!"
});
}
}
It appears what you need to use is an array. This will allow you to store as many coordinates as you want and you'll be able to access them by index (number). For example, if you have 10 coordinates, they could be stored in an array like:
position[i] = array[2]
Your code looks, though, pretty broken, so I think you need more help getting started than what pointed questions on Stack Overflow will get you.
As Gordon says you need an array. If I understand correctly you want to create one marker for each iteration ?
Then I guess something like this would do the trick :
function get_values(numero, array)
{
var i;
var markers = new Array(numero); // create an array to store the markers
for(i=0;i<numero;i++)
{
markers[i] = new google.maps.Marker({
position: array[i],
map: map,
title: "Hello marker " + i // give a different title to each marker based on the number..
});
}
return markers;
}
This assumes that your get_values function takes the number of positions and an array of positions as parameters.