newbie question here..
I'm trying to return the LAT LNG values from the array.
I have the following three functions:
function City(ridge)
{
var city= {
ABC:"Bethel, AK",
ABR:"Aberdeen, SD",
ABX:"Albuquerque, NM"};
return city[ridge];
}
and
function BBox(ridge,product)
{
var yx= {
NOR:
{
ABC:[64.835517,56.735755,-157.448578,-166.284681]
,
ABR:[48.270508,42.631241, -95.331912,-101.483839]
,
ABX:[37.565036,32.726169,-104.179217,-109.457981]}};
var xy=yx[product][ridge];
return {x0:xy[2],x1:xy[3],y0:xy[0],y1:xy[1]};
}
and
function initialize()
{
var ridge = 'ABC';
var product ='NOR';
var getCityInfoFromRidgeName = City(ridge);
var boundries=BBox(ridge,product);
alert(getCityInfoFromRidgeName);
alert(boundries);
}
the alert for City returns "Bethel, AK" as expected..
but
the alert for BBox returns "objec Object" instead of the LAT LNG information as hoped.
I'm probably in over my head, but how can I return the LAT LNG from the BBox to a var?
Den
boundries is an object holding the x and y coords. you can get at the coords with this code:
alert(boundries.x0);
alert(boundries.x1);
alert(boundries.y0);
alert(boundries.y1);
for future reference, objects in javascript can be created like this:
var anObject={property:'value'};
var anotherObject={
message:'Hello',
location:'World',
aNumber:23
};
and then parts of an object can be accessed with a dot - like this:
anObject.property;
alert(anotherObject.message + ' ' + anotherObject.location);
you can learn more about javascript objects here:
http://net.tutsplus.com/tutorials/javascript-ajax/the-basics-of-object-oriented-javascript/
Related
I have this
var markersList = document.getElementById('markersList');
L.MarkerCluster.include({
spiderfy: function(e) {
var childMarkers = this.getAllChildMarkers();
this._group._unspiderfy();
this._group._spiderfied = this;
// Fill the markersList.
markersList.innerHTML = childMarkers
.map((marker, index) => `<li>Marker ${index + 1}:
${marker.getLatLng()}</li>`)
.join('');
// Show the modal.
console.log(markersList);
$(".modalResult").modal('show');
},...
The above gives me in console:
<li>Marker 1: LatLng(45.49934, 9.37966)</li>
<li>Marker 2: LatLng(45.49934, 9.37966)</li>
I need to be able to get as a string 45.49934, 9.37966 since they are the same values, I only need one and I need it as a string as I will have to insert it as an input value later on:
<input type="hidden" value="45.49934, 9.37966">
If I understand your question correctly, then you can extract the lat and lng values from the resut of getLatLng() via the following regular expression:
/(-?\d+.\d*)/gi passed to .match()
This regular expression will extract the two numbers from the result of getLatLng(); one for lat and the other for lng, which can then be combined to aquire the requiredString that you'd use for the input elements value attribute:
{
spiderfy: function(e) {
var childMarkers = this.getAllChildMarkers();
this._group._unspiderfy();
this._group._spiderfied = this;
// Fill the markersList.
markersList.innerHTML = childMarkers.map((marker) =>
`<li>Marker: ${marker.getLatLng()}</li>`).join('');
// If there are any childMarkers
if(childMarkers.length > 0) {
// Match the lat and lng numbers from the string returned by getLatLng()
const [lat, lng] = `${ childMarkers[0].getLatLng() }`
.match(/(-?\d+.\d*)/gi);
// Construct the required string value from the extracted numbers
const requiredString = `${ lat }, ${ lng }`;
// Use requiredString to populate the value attribute of the
// input field in OP
console.log(requiredString);
}
// Show the modal.
console.log(markersList);
$(".modalResult").modal('show');
}
}
You can use children, It like as:
markersList.children[0].innerText
I am trying to convert a lat long string (53.3603, -6.315050000000042) into a google maps object in this format: B: -6.26747649999993 k: 53.339251
I have used this function which works for the long but returns Nan for the lat.
function getLatLngFromString(ll) {
var lat = ll.replace(/\s*\,.*/, ''); // first 123
var lng = ll.replace(/.*,\s*/, ''); // second ,456
var locate = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));
return locate;
}
;
I am storing the lat long in a html tag as it called to a list view connected to a map. It is stored here in the correct format however when I retrieve it using the jQuery .attr it converts it to a string.
var location = $(this).closest('.allList').attr("position");
Any help would be greatly appreciated.
Assuming the lat/lng string looks like "10.5, -0.51"
function getLatLngFromString(ll) {
var latlng = ll.split(/, ?/)
return new google.maps.LatLng(parseFloat(latlng[0]), parseFloat(latlng[1]));
}
Should work
I am using javascript and I have GPS coordinates in the form of a string and I am trying to put those into the google.maps.LatLng(59.327383, 18.06747) format but am having trouble deciding how to do it. I have a variable:
GPSlocation = "(37.700421688980136, -81.84535319999998)"
and I need it to go into that google.maps.LatLng(num, num) format. How can I put this string in there?
Thanks!
You can use standard string operations to extract the values:
var GPSlocation = "(37.700421688980136, -81.84535319999998)";
var LatLng = GPSlocation.replace("(", "").replace(")", "").split(", ")
var Lat = parseFloat(LatLng[0]);
var Lng = parseFloat(LatLng[1]);
google.maps.LatLng(Lat, Lng)
You can create an Array from it (using JSON.parse), and then use apply to 'feed' the coordinates to the method:
GPSlocation = JSON.parse( "(37.700421688980136, -81.84535319999998)"
.replace(/^\(/,'[')
.replace(/\)$/,']')
);
google.maps.LatLng.apply(null,GPSlocation);
Alternatively you can replace the brackets and use split to create an Array, and call the method LatLng the regular way. This method requires an extra conversion to Number of the Array values.
GPSlocation = "(37.700421688980136, -81.84535319999998)"
.replace(/^\(|\)$/,'')
.split(',');
google.maps.LatLng(+GPSlocation[0],+GPSlocation[1]);
To retrieve an Array of coordinates from the string, you could also use:
GPSlocation = ''.slice.call('(37.700421688980136, -81.84535319999998)',
1,this.length-1)
.split(',')
.map(function(a){return +a;});
google.maps.LatLng(GPSlocation[0],GPSlocation[1]);
I'm trying to do something very simple with javascript but can't quite get my head around it. I'm not sure what format I should be passing the var address as.
$(function() {
$('.latlng').each(function(){
var address = $(this).html();
getMap(address);
});
});
function getMap(address) {
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(address),
...
});
}
I'm getting an error when I pass the JQuery ref to normal javascript: TypeError: 'undefined' is not an object (evaluating 'a.position=b'). Any help appreciated.
If I read this correctly and you posted this code correctly, you pass a non-existing object lasting to getMap(), while you want to pass the address object. What happens if you correct this?
jQuery instances are just normal javascript objects like all others, so there should not be a problem.
You're passing the variable latLng to getMap, but its value isn't set. Your ready function at the top should look like this:
$(function() {
$('.latlng').each(function(){
var address = $(this).html();
getMap(this);
});
});
Or, if you're trying to pass the address variable you set, make your ready function look like this:
$(function() {
$('.latlng').each(function(){
var address = $(this).html();
getMap(address);
});
});
Your issue has nothing to do with jquery or javascript.
You are passing the wrong data into the LatLng method.
You need to pass in two parameters to the LatLng method:
...
var mapDiv = $('#mapDiv')[0], // also make sure the div is a regular dom node
lat = 7.1011123,
lng = 4.6667566;
function getMap(address) {
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng( lat, lng ), // you must pass in two parameters
...
});
}
If you are trying to get your LatLng coords from a text div then you need to convert your strings into floats.
Supposing the following html is what you use:
<ul>
<li class="latlng">7.4142335,3.1296874</li>
<li class="latlng">8.4135039,-5.1256828</li>
<li class="latlng">-14.4101158,-5.2810335</li>
</ul>
Then this would be the function running getMap() for every .latlng list item:
$('.latlng').each(function( i ){
var address = $(this).text();
address = address.split(','); // convert your text into an array
// send in your lat and lng strings parsed as floats
getMap(
parseFloat( address[0] ),
parseFloat( address[1] )
);
});
I've got some JSON data that is giving me a list of languages with info like lat/lng, etc. It also contains a group value that I'm using for icons--and I want to build a legend with it. The JSON looks something like this:
{"markers":[
{"language":"Hungarian","group":"a", "value":"yes"},
{"language":"English", "group":"a", "value":"yes"},
{"language":"Ewe", "group":"b", "value":"no"},
{"language":"French", "group":"c", "value":"NA"}
]}
And I want to "filter" it to end up like this:
{"markers":[
{"group":"a", "value":"yes"},
{"group":"b", "value":"no"},
{"group":"c", "value":"NA"}
]}
Right now I've got this, using jQuery to create my legend..but of course it's pulling in all values:
$.getJSON("http://127.0.0.1:8000/dbMap/map.json", function(json){
$.each(json.markers, function(i, language){
$('<p>').html('<img src="http://mysite/group' + language.group + '.png\" />' + language.value).appendTo('#legend-contents');
});
});
How can I only grab the unique name/value pairs in the entire JSON object, for a given pair?
I'd transform the array of markers to a key value pair and then loop that objects properties.
var markers = [{"language":"Hungarian","group":"a", "value":"yes"},
{"language":"English", "group":"a", "value":"yes"},
{"language":"Ewe", "group":"b", "value":"no"},
{"language":"French", "group":"c", "value":"NA"}];
var uniqueGroups = {};
$.each(markers, function() {
uniqueGroups[this.group] = this.value;
});
then
$.each(uniqueGroups, function(g) {
$('<p>').html('<img src="http://mysite/group' + g + '.png\" />' + this).appendTo('#legend-contents');
});
or
for(var g in uniqueGroups)
{
$('<p>').html('<img src="http://mysite/group' + g + '.png\" />' + uniqueGroups[g]).appendTo('#legend-contents');
}
This code sample overwrites the unique value with the last value in the loop. If you want to use the first value instead you will have to perform some conditional check to see if the key exists.
How about something more generic?
function getDistinct(o, attr)
{
var answer = {};
$.each(o, function(index, record) {
answer[index[attr]] = answer[index[attr]] || [];
answer[index[attr]].push(record);
});
return answer; //return an object that has an entry for each unique value of attr in o as key, values will be an array of all the records that had this particular attr.
}
Not only such a function would return all the distinct values you specify but it will also group them if you need to access them.
In your sample you would use:
$.each(getDistinct(markers, "group"), function(groupName, recordArray)
{ var firstRecord = recordArray[0];
$('<p>').html('<img src="http://mysite/group' + groupName+ '.png\" />' + firstRecord.value).appendTo('#legend-contents');
}
See this-
Best way to query back unique attribute values in a javascript array of objects?
You just need a variation that checks for 2 values rather than 1.
var markers = _.uniq( _.collect( markers , function( x ){
return JSON.stringify( x );
}));
reference