passing jquery element reference to vanilla javascript - javascript

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

Related

C# razor object is not defined on click

I have following code in my index.cshtml where a FoursquareInfo object is beeing created.
#using WebMatrix.Data;
#using CanYouPay.Models.FoursquareAPI;
#{
FoursquareInfo fsInfo = new FoursquareInfo();
Checkins response = new Checkins();
Checkin checkins = new Checkin();
List<RootItem> items = new List<RootItem>();
RootItem item = new RootItem();
Venue venue = new Venue();
Location loc = new Location();
loc.lat = 51.19189444478925;
loc.lng = 4.664656084372357;
venue.location = loc;
item.venue = venue;
items.Add(item);
checkins.items = items;
response.checkins = checkins;
fsInfo.response = response;
}
I have a div in my html code for the index.cshtml where the updateMap(fourSquareInfo) method is called when clicked.
<div id="mapBtn" onclick="updateMap(#fsInfo)" class="btn btn-success btn-lg col-md-2 pull-right">Show Map!</div>
My updateMap function is:
function updateMap(foursquareInfo) {
var uluru = { lat: 20, lng: 30 };
var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
Yes, for testing purposes I don't do anything with the foursquareInfo object passed - the lat and long values will be replaced by the foursquareInfo ones when I can fix the error I receive when the onClick event happens:
CanYouPay is not defined at HTMLDivElement.onclick
What is wrong with my html/razor/js code?
As per my comments: Looks like you are trying to pass a c# object into your js - if you view source on that button, it is probably going to be some text including CanYouPay and as you have not defined it as a js variable, it will throw an error, you would either need to create a js object and map your c# object values to it, or pass through a bunch of strings
Option 1 create a js object that matches your c# object and in your razor you can map the values:
<script>
// this needs to be in your razor before the onclick (so object is created before you use it)
var fsJSObject = new fsJSObject(); // this object should match your c# object
fsJSObject.StringValue = '#fsInfo.StringValue'; // this needs to be the final value - eg a string, int, date, etc - cannot be another object, otherwise you will get a similar mistake to above
fsJSObject.IntValue= #fsInfo.IntValue;
// pass fsJSObject into your onclick function
</script>
Option 2, pass the values directly into the function
onclick="updateMap('#fsInfo.StringValue', #fsInfo.IntValue, '#fsInfo.AnotherStringValue')"
Notice the quotes around the string values
When I try to build up the same page using razor I see I get the following in my page:
<div id="mapBtn" onclick="updateMap(WebApplication1.Models.FoursquareInfo)" class="btn btn-success btn-lg col-md-2 pull-right">Show Map!< /div>
As you see Razor will directly set the object which is to say the class name. In this case, I would advise to directly set the location numbers in the call like:
<div id="mapBtn" onclick="updateMap(#loc.lat, #loc.lng)" class="btn btn-success btn-lg col-md-2 pull-right">Show Map!< /div>
And then in the call on the server side build up the object and do what you want with it. Remember you'll have to rebuild the object every time you do a new call to the server: the objects are not kept in memory. It is advised to only put the information in the view that view actually needs instead of your entire serverside object.

Extract multiple data from DOM in jQuery?

There is a node like this
<img src=​"http:​/​/​x.JPG" data-latitude=​"0" data-longitude=​"0">​
In jQuery, I can extract two data attribute like this:
a=node.data("latitude")
b=node.data("longitude")
I was wondering whether there is a way to extract multiple data attributes in one time, like this:
latLng = node.data([latitude, longitude]) // not working
latLng = node.data();
this return object
{
latitude:0,
longitude:0
}
I was wondering whether there is a way to extract multiple data
attributes in one time, like this:
latLng = node.data([latitude, longitude]) // not working
Note, Not certain if expected result is array of values from .node.data() ?
var data = $.map($("img").data(), function(value) {
return value
});
console.log(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<img src=​"http:././.x.JPG" data-latitude="0" data-longitude="0">
DEMO
var latLng = $('img').data();
$.each(latLng,function(index,value){
alert(value);
});

Convert lat long string into google maps API LatLng Object

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

Using string variable as a json object name

I have a dynamic string variable created by UI (valkey in below code) and I want to use that variable as a JSON key to get a value from TestObj which is a JSON object. But an attempt with the following code has returned an error.
var valkey=$('#cityfrm').val()+"_TO_"+$('#cityto').val();
if($('#cityfrm').val()!="NIL" || $('#cityto').val()!="NIL")
{
$.each(TestObj.valkey, function() {
var durn=this.duration;
var prc=this.price;
var curlegs=this.legs;
// updating ui
});
}
I appreciate any help.
TestObj.valkey will look for the key valkey in TestObj, which is undefined in your case that is why you are getting the error.
If you want to look for a key from a variable you need to use the syntax TestObj[valkey].
Ex:
var valkey=$('#cityfrm').val()+"_TO_"+$('#cityto').val();
if($('#cityfrm').val()!="NIL" || $('#cityto').val()!="NIL") {
$.each(TestObj[valkey], function() {
var durn=this.duration;
var prc=this.price;
var curlegs=this.legs;
// updating ui
});
}

Using a string as GPS coordinates

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

Categories