Using JSON in C # and adding points in GMAPS

2

Good morning,

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

I have a page where the user enters the comments (and the page captures latitude and longitude) and saves it 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 JSON file of the tutorial, latitude and longitude are added manually in JSON and in my case, I need to add the points from the database.

Follow 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><!--Caixadeinformação--><scriptsrc="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 JSON return and looks 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"
}
]

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

Does anyone have any light?

Thank you in advance!

    
asked by anonymous 13.10.2015 / 13:01

1 answer

1

I think the problem is with the return of your Carregar() method. The JavascriptSerializer returns a JSON string , not a JSON object.

To be able to handle the return JSON, you must first make a parse :

var pontosJson = JSON.parse(pontos);

In addition, do not use $(pontos).each(function (i) {}) to iterate under an array and / or object, this jQuery function is only to iterate under jQuery elements. The correct one is to use the $.each ( link ) function, which is suitable for objects and arrays:

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

});
    
13.10.2015 / 14:07