Reputation: 271
I've got a Web Application with C# code that creates a list of objects with their long and lat. I want to then create marker points on Google Maps for them using Javascript. I've currently got this code:
var marker;
for (var i = 0; i < ('<%= Buses.Count %>' - 1); i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng('<%= Buses['i'].latitude %>', '<%= Buses['i'].longitude %>'),
map: map
});
}
Which does not work, I believe the error is with where I reference "i" to say which object in the list to use.
If I manually set a marker point without a for loop and change ['i'] to [0] it will place a marker fine. However, due to the number of items changing and reaching up to 100 I require using a for loop. I have tried removing the '' around i and this generates an error saying
"i does not exist in the current context."
I have seen these posts: Add two marker points in google maps
Google Maps JS API v3 - Simple Multiple Marker Example
Google Maps JS API v3 - Simple Multiple Marker Example
However, all of these are using locations inside of the JavaScript. My objects are contained within the C# code as a custom object defined as:
public static List<Bus> Buses = new List<Bus>();
This is my C# Code in full: https://pastebin.com/2M1hWjnM
Upvotes: 2
Views: 2102
Reputation: 28
You're mixing a javascript for with data in code-behind/C#. It not works. First, you've to put the marks data on a javascript array. Then make your for without webforms tags <%%>
put something like this on your page code behind (C#)
public static string getBusesJson()
{
var buses = new List<Bus>();
buses.Add(new Bus() {latitude = 10, longitude = 20 });
buses.Add(new Bus() { latitude = 15, longitude = 30 });
buses.Add(new Bus() { latitude = 5, longitude = 40 });
return JsonConvert.SerializeObject(buses);
}
put this on your aspx header:
<script type="text/javascript">
var points = <%= WebApplication3.WebForm1.getBusesJson()%>;
for (var i = 0; i < points.length; i++) {
//pass points[i].latitude and points[i].longitude to google maps
}
</script>
Upvotes: 1