Using JSON in c# and adding points in GMAPS

Asked

Viewed 470 times

2

Good morning, everyone,

I’m developing a C# web application that uses GMAPS to add comments to addresses.

I have a page on which the user inserts comments (and the page captures latitude and longitude) and saves to a Mysql database.

I found a nice tutorial that shows how to insert the points through a JSON document.

The problem is that in the tutorial’s JSON file, the latitude and longitude are added manually in JSON and in my case, I need to add points from the database.

Follows my code:

index aspx.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="testeMapa.index" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 <link rel="stylesheet" type="text/css" href="css/estilo.css">
<title></title>
</head>
<body>
<form id="form1" runat="server">

    <div id="mapa" style="height: 500px; width: 700px">
    </div>

    <script src="js/jquery.min.js"></script>

    <!-- Maps API Javascript -->
    <script src="http://maps.googleapis.com/maps/api/js?sensor=false">               </script>

    <!-- Caixa de informação -->
    <script src="js/infobox.js"></script>

    <!-- Agrupamento dos marcadores -->
    <script src="js/markerclusterer.js"></script>

    <!-- Arquivo de inicialização do mapa -->
    <script src="js/mapa.js"></script>

    <asp:GridView ID="gvTeste" runat="server"></asp:GridView>
    <asp:Label ID="lblteste" runat="server" Text="Label"></asp:Label>
</form>
</body>
</html>

index.aspx.Cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using System.Data;
using MySql.Data.MySqlClient;
using System.Reflection;

namespace testeMapa
{
public partial class index : System.Web.UI.Page
{
    private MySqlConnection mConn;
    private MySqlDataAdapter mAdapter;
    private DataSet mDataSet;

    protected void Page_Load(object sender, EventArgs e)
    {

        mConn = new MySqlConnection("server=192.185.176.186;User Id= ***** ;database=ondli012_buscmob; password=****");
        mConn.Open();

        MySqlCommand com = new MySqlCommand();
        com.Connection = mConn;
        com.CommandText = "Select idDado, latitudeEnd, longitudeEnd, enderecoDado from inserirDados";
        MySqlDataReader dr = com.ExecuteReader();
        DataTable dt = new DataTable();
        dt.Load(dr);




    }

                  [WebMethod]
    static public string Carregar(DataTable dt )
    {


        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
        Dictionary<string, object> childRow;
        foreach (DataRow row in dt.Rows)
        {
            childRow = new Dictionary<string, object>();
            foreach (DataColumn col in dt.Columns)
            {
                childRow.Add(col.ColumnName, row[col]);
            }
            parentRow.Add(childRow);
        }

            var pontos = jsSerializer.Serialize(parentRow);


            return pontos;

        }
        }
    }

And finally the Javascript:

var map;
var idInfoBoxAberto;
var infoBox = [];
var markers = [];

function initialize() {
var latlng = new google.maps.LatLng(-18.8800397, -47.05878999999999);

var options = {
    zoom: 5,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};

map = new google.maps.Map(document.getElementById("mapa"), options);
}

initialize();

function abrirInfoBox(id, marker) {
if (typeof (idInfoBoxAberto) == 'number' && typeof    (infoBox[idInfoBoxAberto]) == 'object') {
    infoBox[idInfoBoxAberto].close();
}

infoBox[id].open(map, marker);
idInfoBoxAberto = id;
}

function carregarPontos() {



    $.ajax({
        type: 'POST',
        url: '/index.aspx/Carregar',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (pontos) {

            var latlngbounds = new google.maps.LatLngBounds();

            $(pontos).each(function (i) {

                var lat = pontos[i].latitudeEnd;
                var long = pontos[i].longitudeEnd;
                var endereco = pontos[i].enderecoDado;
                var idDados = pontos[i].idDado;

                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(lat, long),
                    title: "Meu ponto personalizado! :-D",
                    icon: 'img/marcador.png'
                });

                var myOptions = {
                    content: "<p>" + endereco + "</p>",
                    pixelOffset: new google.maps.Size(-150, 0)
                };

                infoBox[idDados] = new InfoBox(myOptions);
                infoBox[idDados].marker = marker;

                infoBox[idDados].listener =    google.maps.event.addListener(marker, 'click', function (e) {
                    abrirInfoBox(idDados, marker);
                });

                markers.push(marker);

                latlngbounds.extend(marker.position);

            });

            var markerCluster = new MarkerClusterer(map, markers);

            map.fitBounds(latlngbounds);

        }  });

}

carregarPontos();

I tested the return of JSON and it stays like this:

[
{
"idDado": 11,

"latitudeEnd": "-22.8668838",
"longitudeEnd": "-43.307824100000005",
"enderecoDado": "R. Limeira, 16 - Tomás Coelho, Rio de Janeiro - RJ, 21370-  460, Brasil"
},
{
"idDado": 10,
"latitudeEnd": "-22.9501581",
"longitudeEnd": "-43.18422179999999",
"enderecoDado": "Botafogo - Botafogo, Rio de Janeiro - RJ, Brasil"
},
{
"idDado": 24,
"latitudeEnd": "-20.1940458",
"longitudeEnd": "-44.935004400000025",
"enderecoDado": "R. Limeira - Floresta, Divinópolis - MG, Brasil"
},
{
"idDado": 17,
"latitudeEnd": "-22.878278665030688",
"longitudeEnd": "-43.2732975914364",
"enderecoDado": "Av. Pastor Martin Luther King Junior, 4667-4713 - Inhaúma, Rio de Janeiro - RJ, Brasil"
}
]

I copy this return and put it in a file. JSON and change the javascript, it works perfectly... but if I try to get JSON created dynamically, does not load the points..

Someone has some light?

Thanks in advance!

  • Already tried parse the data and transform it into an array?

1 answer

1

I believe the problem lies in the return of your method Carregar(). The JavascriptSerializer returns a JSON string, and not a object JSON.

In order to be able to manipulate the return JSON, you must first make a parse:

var pontosJson = JSON.parse(pontos);

Also, do not use $(pontos).each(function (i) {}) to iterate under an array and/or object, this function of jQuery is only to iterate under jQuery elements. The correct is to use the function $.each (http://api.jquery.com/jquery.each/), which is suitable for objects and arrays:

$.each(pontos, function(i, ponto) {

});
  • parse I do before returning to Codebehind or java?

  • You do it in javascript, right after the return of the ajax call, in the function Success

  • nothing happened =( do not know if I did right: 'Success: Function (points) { var pointsJson = JSON.parse(points); points = pointsJson;'

  • Have you checked whether the method Carry() is actually returning a JSON correctly? He expects to receive an object of type Datatable, but I saw his call Ajax is not passing this parameter. In function Success, give a console.log(points) and see if JSON is actually being returned.

  • I noticed this and corrected.. I created a global variable DT and removed the Load parameter.. for ease, I have placed on the web http://www.buscmob.somee.com/listaDados.aspx/Carregar

  • Objectd: "[{"idDado":11,"latitudeEnd":"-22.8668838","longitudeEnd":"-43.307824100000005","addresseDado":"R. Limeira, 16 - Tomás Coelho, Rio de Janeiro - RJ, 21370-460, Brazil"},"}]"proto: Object had to shorten the answer because it exceeded the limit...

  • my server crashed =(

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.