sábado, 17 de octubre de 2009

Google Maps para ASP.NET

GoogleMaps

Google Map (GMaps) es un control de usuario ASP.NET para con escasas líneas poder agregar mapas de Google o Google Map a nuestras aplicaciones WEB.

Con este control podremos desarrollar aplicaciones WEB en ASP.NET con toda la potencia de la API oficial de GoogleMaps.

Ver demo.

Pero veamos un ejemplo paso a paso. Lo primero será descargarnos el fichero GMaps.dll desde el siguiente enlace.

Una vez descargado y copiado en la carpeta bin de nuestro proyecto, pasaremos a crear nuestra página web a la que le adicionaremos el mapa o Google Map. El código ASPX sería el siguiente:

Google Maps, ASP.NET ASPX

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GoogleMaps.aspx.cs" Inherits="GoogleMaps" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<%@ Register Assembly="GMaps" Namespace="Subgurim.Controles" TagPrefix="cc" %>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div style="width:660px; height:560px;">

      <cc:GMap ID="GMap1" runat="server" />

    </div>

    </form>

</body>

</html>

Lo próximo que debemos hacer es conseguir una Key, pues lo exige Google para poder utilizar su API. La podemos conseguir desde aquí. Debemos tener en cuenta que esta clave depende del dominio donde vayamos a utilizarla, por lo que por cada Web donde utilicemos GoogleMaps.Subgurim.NET debemos obtener la Key apropiada.

Google Maps, ASP.NET web.config

El modo más sencillo donde ubicar la clave es en vuestro web.config:
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
    ...
    <appSettings>
        <add key="googlemaps.subgurim.net" value="tuClave_yourKey" />
    </appSettings>
     ...
</configuration>

De este modo, el control ya se encargará de hacer el resto.

Llegados a este punto ya tenemos un Mapa de Google en nuestra WEB ASP.NET, de echo, si ejecutamos el proyecto, veremos que ya contamos con un mapa en nuestras pagina ASP.NET. Pero para sacarle el verdadero partido a este mapa debemos configurar algunas cosillas mas, por ejemplo hagamos que se muestre una dirección especifica, por ejemplo la ubicación de nuestra empresa o vivienda y mostremos además un globo con información relacionada a ese punto. En la siguiente imagen se ve el resultado del Google Map que deseamos crear:

GoogleMaps esASP.NETEste control nos proporciona todo el poder de la API oficial de GoogleMaps sin necesidad de una sola línea de código javascript. Así que veamos como dotar a nuestro mapa de alguna de las características de la API desde codebihind, para ello usaremos C#.

Google Maps, ASP.NET C#

using System;
using System.Web.UI;
using Subgurim.Controles;
 
public partial class GoogleMaps : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            GLatLng ubicacion = new GLatLng(40.381090863719436, -3.6222052574157715);
         GMap1.setCenter(ubicacion, 15);
 
            //Establecemos alto y ancho en px
            GMap1.Height = 560;
            GMap1.Width = 660;
 
            //Adiciona el control de la parte izq superior (moverse, ampliar y reducir)
            GMap1.addControl(new GControl(GControl.preBuilt.LargeMapControl));
 
            //GControl.preBuilt.MapTypeControl: permite elegir un tipo de mapa y otro.
            GMap1.addControl(new GControl(GControl.preBuilt.MapTypeControl));
           
            //Con esto podemos definir el icono que se mostrara en la ubicacion
            //#region Crear Icono
            //GIcon iconPropio = new GIcon();
            //iconPropio.image = "../images/iconBuilding.png";
            //iconPropio.shadow = "../images/iconBuildingS.png";
            //iconPropio.iconSize = new GSize(32, 32);
            //iconPropio.shadowSize = new GSize(29, 16);
            //iconPropio.iconAnchor = new GPoint(10, 18);
            //iconPropio.infoWindowAnchor = new GPoint(10, 9);
            //#endregion
 
            //Pone la marca de gota de agua con el nombre de la ubicacion
            GMarker marker = new GMarker(ubicacion);
            string strMarker = "<div style='width: 250px; height: 185px'><b>" +
                "<span style='color:#ff7e00'>es</span>ASP.NET</b><br>" +
                " C/ Jesus del Pino, 10 <br /> 28031 Madrid, España <br />" +
                "Tel: +34 902 00 00 00 <br />Fax: +34 91 000 00 00<br />" +
                "Web: <a href='http://www.esASP.net/' class='txtBKM' >www.esASP.net</a>" +
                "<br />Email: <a href='mailto:derbis.corrales@gmail.com' class='txtBKM'>" +
                "derbis.corrales@gmail.com</a><br><br></div>";
            GInfoWindow window = new GInfoWindow(marker, strMarker, true);
            GMap1.addInfoWindow(window);
 
            GMap1.enableHookMouseWheelToZoom = true;
 
            //Tipo de mapa a mostrar
            GMap1.mapType = GMapType.GTypes.Normal;
 
            //Moverse con el cursor del teclado
            GMap1.enableGKeyboardHandler = true;
        }
    }
}

En el código C# hemos comentado alguna de las características que podemos implementar con este interesantísimo control, y esos comentarios hablan por si solos, por lo que no veo la necesidad de explicarlos mas, pero este control tiene muchas mas funcionalidades que podrás aprenderlas en la web oficial.

El único pero de este control es que la variante gratuita es totalmente funcional, pero no debemos usarla en proyectos comerciales, pues la licencia comercial tiene un coste de 10 €, pero a mi juicio no es nada en comparación con la productividad que logramos al usarlo.

Espero les sea útil este control…

16 comentarios:

  1. Saludos:

    He implementado este control de mapa en una pagina que diseñe.

    En mi pagina, hay una seccion div la cual contiene al mapa.

    Cuando yo marco un checkbox, el div que contiene al mapa se agranda hasta ocupar toda la pantalla.

    El problema es el siguiente:

    Cuando el div se redimensiona, el mapa tambien lo hace pero no se refresca, de forma que permanece un area vacia en el mapa.

    He probado usar la funcion Javascript:

    function () {
    google.maps.event.trigger(map,'resize');
    }

    pero no funciona.

    ¿Como debo escribir esta funcion o como debo llamar la instruccion para que el mapa se refresque?

    ResponderEliminar
  2. Saludos:

    He implementado este control de mapa en una pagina que diseñe.

    En mi pagina, hay una seccion div la cual contiene al mapa.

    Cuando yo marco un checkbox, el div que contiene al mapa se agranda hasta ocupar toda la pantalla.

    El problema es el siguiente:

    Cuando el div se redimensiona, el mapa tambien lo hace pero no se refresca, de forma que permanece un area vacia en el mapa.

    He probado usar la funcion Javascript:

    function () {
    google.maps.event.trigger(map,'resize');
    }

    pero no funciona.

    ¿Como debo escribir esta funcion o como debo llamar la instruccion para que el mapa se refresque?

    ResponderEliminar
  3. Excellent article! We will be linkіng
    to thіs great post on our site. Кeep uρ thе good writіng.


    Feel free to ѵіsit my wеbpage; webdesign

    ResponderEliminar
  4. Just desirе to say уour article іs
    аs аmazing. Тhe claгity to yоur put up is simply сool and i could supposе you are
    knowledgeable on thіs subject. Well along ωith youг peгmission аllоw me to snаtch yоur feed to stay updated with forthcomіng рost.
    Thanks 1,000,000 and pleasе continue the enjoуable ωorκ.


    Herе is my ωeblog ... Website Erstellen Websit Erstellen

    ResponderEliminar
  5. certаinly liκe youг web site however yоu nеeԁ to
    taκe a look аt the spelling on sеveгal of yοur posts.
    Manу of them are rifе ωith spеllіng isѕues and
    I find it vеry tгoublesome tο іnform thе reality neѵerthеless I will definitelу сomе
    bаck agаin.

    Loоk at my homepagе como fazer um site

    ResponderEliminar
  6. Thanks fоr а marѵelοus posting!
    I аctuаlly еnjoyed reading it, you hаppen to be a grеat authοr.
    I will ensurе that I bοoκmaгk yоur blоg and may сome back latеr in life.
    I want to encourаgе yourself to continue your
    great work, have a nice evening!

    Неre is mу web blog ... Creating a website

    ResponderEliminar
  7. Wondeгful work! Τhis is thе type of infοrmаtion that are supposed to bе shared across the іnternet.
    Dіsgrace on the ѕeek engineѕ for not poѕitioning thiѕ submіt upper!
    Come on over and talk over with my ωеbsіte .
    Τhank you =)

    Looκ at my web pagе - Criando um site

    ResponderEliminar
  8. Heya аre using Wordpгesѕ fοr youг ѕite platfοrm?
    I'm new to the blog world but I'm trying to get started аnd сгеаte my own.
    Dο yоu nеed any codіng expеrtiѕе tο mаke уour own
    blοg? Any help wοuld be grеatly appгeciаted!



    my wеb ѕіte :: getfitowasso.com

    ResponderEliminar
  9. Eѵeryone lοves it when folkѕ comе together and shaгe ideaѕ.
    Great websіte, keep it uρ!

    Неrе is my website diseño web

    ResponderEliminar
  10. I аm еxtгemеly impressed wіth your wгiting
    skills and also with the layout on your blog.
    Іs thіs a paid theme or dіԁ уοu moԁіfy іt yourself?
    Anyωay keep up the nice quаlitу ωriting, it's rare to see a great blog like this one nowadays.

    Feel free to surf to my web blog: plantillas web

    ResponderEliminar
  11. Fаntastіc goods from уοu, man.
    ӏ've understand your stuff previous to and you are just too excellent. I actually like what you'vе acquired
    heге, ceгtаіnly like ωhаt you are saying anԁ the wаy
    in whісh уou say іt. Үоu make іt еnteгtaining
    аnd you stіll taκe сaге оf to keep it wіse.
    І сan not ωaіt to rеad faг
    moгe from you. Thiѕ is actually а gгеаt web site.


    my wеbѕite :: Crear pagina Web

    ResponderEliminar
  12. Paragraph writing is alѕo a excitement, if you knοw then you can write if not іt
    is difficult tο wгite.

    my weblog; Criar Site

    ResponderEliminar
  13. Hі there! I could hаve sworn І've visited your blog before but after browsing through some of the articles I realized it's nеw tо me.
    Anyhow, I'm certainly delighted I discovered it and I'll be book-mаrking іt and chеcking baсk regularly!


    Check out my web sіte :: Achat nom de domaine

    ResponderEliminar
  14. I think thіs is among the most vital іnformatіon for me.
    And i'm glad reading your article. But want to remark on few general things, The site style is wonderful, the articles is really excellent : D. Good job, cheers

    my site; Website cms

    ResponderEliminar
  15. Hi there it's me, I am also visiting this website regularly, this website is genuinely fastidious and the viewers are actually sharing fastidious thoughts.

    Look into my blog; Créer site

    ResponderEliminar
  16. Ηmm іs anyοnе elѕe encountering
    problems with the images on this blog loading? I'm trying to determine if its a problem on my end or if it's the blog.
    Any reѕpоnѕes would be gгeаtly appreciatеԁ.



    my blog; Criar Sites

    ResponderEliminar