3
votes

I'm trying to create a map with markers with Latitude and Longitude that comes from the database. With the Lat and Lng that is in the database i'm trying to pass it to a javascript file.

This code is from aspx.cs and gets the variables Lat and Lng. I created labels lblLat and lblLng just to see on the page if it gets the right data.

Here is the code from aspx.cs:

    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionCarpool"]);

        DataRow dr = ExecuteDataSet(("SELECT Lat, Lng FROM Users Where UserID=1").ToString()).Tables[0].Rows[0];

        Mapa prd = new Mapa();

        prd.Lat = dr["Lat"].ToString();
        prd.Lng = dr["Lng"].ToString();

        lblLat.Text = prd.Lat;
        lblLng.Text = prd.Lng;

        conn.Close();
    }

On my Javascript file, it makes the map appear but not the marker with the Lat and Lng. The part marker is where it should get the "Lat" and "Lng" thats on the file aspx.cs. The part "position: new google.maps.LatLng(41, -8)" works fine but on the part "position: new google.maps.LatLng("Lat", "Lng")" is where i want to get the data from the database on aspx.cs. On the aspx.cs file it gets the right data but now im just trying to find a way to pass that data to Lat and Lng thats on the Javascript file.

Here is my Javascript code:

function initialize() {

var latlng = new google.maps.LatLng(41.563059,-8.624268);
var myOptions = {
    zoom: 7,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: latlng
}
var map = new google.maps.Map(document.getElementById("map"), myOptions);

var marker = new google.maps.Marker({
    //position: new google.maps.LatLng(41, -8),
    position: new google.maps.LatLng("Lat", "Lng"),
    map:map   
});

}

Can anyone help my with this? I really apreciate it. Thanks!

5

5 Answers

3
votes

You can place

<input type=hidden />

control(s) on page and fill them with values of Lat and Lng. Then read it using javascript.

1
votes

You don't really "send values to JavaScript from ASP.NET." The former is client-side code, the latter is server-side code. Keeping the two intuitively separated will make your web development life a lot easier. So ideally you'd probably be looking to emit those values to the client-side code in a way that the JavaScript can find it when it runs.

If you can successfully set the value of fields on the page then your JavaScript code can just access those fields' values:

var lat = document.getElementById('someElement').value
0
votes

I would actually use a web service for this with Json. In your javascript file, just use this code. You will have to pass some sort of ID for your event, so it returns the correct lat and lng. This will allow you to get data from the server in a javascript file.

function  initialize() {

var lat; 
var lng; 
var ID = 1; //change this to your ID

    $.ajax({
        type: "POST",
        async: false,
        contentType: "application/json; charset=utf-8",
        url: "MyWebService.asmx/ReturnData",
        data: "{'IdOfEvent':'" + ID + "'}",
        dataType: "json",
        success: function(result) {

            //render the new lat & long from the database
            var Coordinates = (eval(result.d));

            $.each(Coordinates , function(key, value) {

                Lat = value.Lat;
                Lng = value.Lng;

            });
        },
        error: function (xhr, textStatus, errorThrown) {
            alert("Error - " + textStatus);
            revertFunc();
        }

var latlng = new google.maps.LatLng(41.563059,-8.624268);
var myOptions = {
    zoom: 7,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: latlng
}
var map = new google.maps.Map(document.getElementById("map"), myOptions);

var marker = new google.maps.Marker({
    position: new google.maps.LatLng(Lat, Lng),
   // position: new google.maps.LatLng("Lat", "Lng"),
    map:map   
});

    });

WebService:

using Newtonsoft.Json; //download this


 [WebMethod]
    public string ReturnData(int IdOfEvent)
    {

        SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionCarpool"]);

        DataRow dr = ExecuteDataSet(("SELECT Lat, Lng FROM Users Where UserID=" + IdOfEvent).ToString()).Tables[0].Rows[0];

        Mapa prd = new Mapa();
        List<Mapa> lst = new List<Mapa>(); 

        prd.Lat = dr["Lat"].ToString();
        prd.Lng = dr["Lng"].ToString();

        lst.Add(prd);  


        JavaScriptSerializer js = new JavaScriptSerializer();
        string strJSON = js.Serialize(lst.ToArray());
        return strJSON; 


    }

See if this works. Let me know if you have questions.

0
votes

Why not change your initialize() function to have the following :

var latlng = new google.maps.LatLng(myLat,-myLong);

And then when you render the page, include some in stream JavaScript along the lines of

<script type="text/javascript">
var myLat = 41;
bar myLong = -8;
</script>

Just make sure your instream JavaScript is executed before the initialize() function

-1
votes

In your aspx page, somewhere, render this:

<div id="marker" runat="server" style="display:none;">
    <div id="marker_lat" runat="server">41</div>
    <div id="marker_lng" runat="server">-8</div>
</div>

This should be pretty straightforward. You should be able to set the text or html property from codebehind. (It's been so long since I did webforms, I'm not sure what the property name is for the HtmlControls.)

The next part will require you to have the jquery script library, if it isn't already loaded on your page:

var lat = $('#marker_lat').html();
var lng = $('#marker_lng').html();
var marker = new google.maps.Marker({
    position: new google.maps.LatLng(lat, lng),
    map:map   
});