[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Need Google maps geocoding to center map on initialize

Posted on 2013-05-25
2
Medium Priority
?
334 Views
Last Modified: 2013-05-30
Hi,

I am using Google Maps API v3 for a map with Directions Service. Everything is working fine, but I want to be able to automatically load in an end location, make it the map center, and Display the map (without directions) when the page is loaded.

In .NET, on page load I am loading in the location (Mylocationaddress). But I want to use the Geocoder to take that address and make it the map center (with a marker).

I have played around with the Geocoder code ( function codeAddress() below) but can't figure out how to connect it up.

Again, on load I just want the map to load with the end location in the map center. The Directions should not be displayed.


<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data" %>

<script runat="server">
    Dim MyLocation, MyAddress, FromAddress as String
    Dim cmd As New SqlCommand()
    Dim TransReader As SqlDataReader
    Dim MyConn As New SqlConnection(ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString)
    Dim Ttext(26) As String
    Dim Homelocnum as Integer
    Dim Soccertitle, Hockeytitle, Fromlabel, Tolabel, Orlabel, ShowdirectionsButton, printButton, Mylocationaddress, Displaylang, Dirtitle, ToSelect, FromSelect, Homelocation as String
    Dim MyTools As New Krylium.KryliumTools

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        
        If Not Page.IsPostBack() Then
            
            Mylocation = Request.Querystring("locnum")
                
            ' Load the appropriate language files

            Ttext = MyTools.LoadTranslation("showlocation", MyTools.GetLanguage)
            If MyTools.GetLanguage = "english" then
                Displaylang = "en"
            else
                Displaylang = "fr"
            End If

            Ttext = MyTools.LoadNewTranslation("showlocation", MyTools.GetLanguage)
            Soccertitle = Ttext(1)
            Hockeytitle = Ttext(2)
            Fromlabel = Ttext(3)
            Tolabel = Ttext(4)
            Orlabel = Ttext(5)
            showdirectionsButton = Ttext(6)
            printButton = Ttext(7)
      
            cmd.Connection = MyConn
            cmd.Connection.Open()

            ' Find the sport
            cmd.CommandText = "Select leaguetype from leaguesetup where leaguenum = " & Session("leaguenum")
            If cmd.ExecuteScalar() = "hockey" then
                Dirtitle = Hockeytitle
            else
                Dirtitle = Soccertitle
            End If

            ' Find the homefield
            cmd.CommandText = "Select homelocnum from leaguesetup where leaguenum = " & Session("leaguenum")
            Homelocation = cmd.ExecuteScalar()
        
            ' Load in all the to: locations

            ' Initialize the Select string
            ToSelect = "<select id='select_to'><option value=''>--------</option>"
            FromSelect = "<select id='select_from'><option value=''>--------</option>"

            ' Load in the locations, but select the one we are looking for
            cmd.CommandText = "Select Locname, Locnum, Streetnum + ' ' + Streetname + ', ' + City + ', ' + Region as Locaddress from locations where leaguenum = " & Session("leaguenum")
            TransReader = cmd.ExecuteReader()		
            While TransReader.Read()
                If TransReader("locnum") = Mylocation then
                    ToSelect = ToSelect & "<option value='" & TransReader("Locaddress") & "' selected>" & TransReader("Locname") & "</option>"
                    Dirtitle = Dirtitle & " (" & TransReader("Locname") & ")"
                    Mylocationaddress = TransReader("Locaddress")
                else
                    ToSelect = ToSelect & "<option value='" & TransReader("Locaddress") & "'>" & TransReader("Locname") & "</option>"        
                End If
                If TransReader("locnum") = Homelocation then
                    FromSelect = FromSelect & "<option value='" & TransReader("Locaddress") & "' selected>" & TransReader("Locname") & "</option>"
                else
                    FromSelect = FromSelect & "<option value='" & TransReader("Locaddress") & "'>" & TransReader("Locname") & "</option>"        
                End If
            End While
		    TransReader.Close()
            ToSelect = ToSelect & "</select>"
            FromSelect = FromSelect & "</select>"
            cmd.Connection.Close()
        End If

End Sub

</script>

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <meta content="IE=edge,chrome=1" />
    <link href="../Styles/KryliumStyles.css" rel="stylesheet" />
    <title>Displaying text directions with <code>setPanel()</code></title>
    <style>
        html { height: 100% }
      body { height: 100%; margin: 0; padding: 0; width: 900px }
      #directions-panel {
        height: 100%;
        width: 400px;
      }

      #map-canvas {
        width: 500px;
        height: 100%;
        float: left;
        margin-right: 15px;
        margin-left: 10px;
        margin-top: 10px;
      }

      #control {
        background: #fff;
        padding: 5px;
        font-size: 14px;
        font-family: Arial;
        border: 1px solid #ccc;
        box-shadow: 0 2px 2px rgba(33, 33, 33, 0.4);
        margin-left: 10px;
        margin-top: 6px;

      }

      @media print {
        #map-canvas {
          height: 500px;
          margin: 0;
          float: none;
        }

        #directions-panel {
          float: none;
          width: auto;
        }
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAK14kauUVFerRk9MwJGTwnsUo7wNH0cDw&sensor=false&language=<%=Displaylang%>"></script>
    <script>

        var directionsDisplay;
        var directionsService = new google.maps.DirectionsService();
        var map;
        var geocoder;

        function initialize() {
            directionsDisplay = new google.maps.DirectionsRenderer();
            var latlng = new google.maps.LatLng(45.5, -73.55);
            var mapOptions = {
                zoom: 7,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                center: latlng
            }
            map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
            directionsDisplay.setMap(map);
            directionsDisplay.setPanel(document.getElementById("directionsPanel"));

        }

        function calcRoute() {
            if (document.getElementById("select_from").value != "") {
                start = document.getElementById("select_from").value;
            } else {
                start = document.getElementById("text_from").value;
            }
            if (document.getElementById("select_to").value != "") {
                end = document.getElementById("select_to").value;
            } else {
                end = document.getElementById("text_to").value;
            }

            var request = {
                origin: start,
                destination: end,
                travelMode: google.maps.TravelMode.DRIVING
            };
            directionsService.route(request, function (response, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                }
            });
        }

        function codeAddress() {
            var address = document.getElementById("address").value;
            geocoder.geocode({ 'address': address }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    map.setCenter(results[0].geometry.location);
                    var marker = new google.maps.Marker({
                        map: map,
                        position: results[0].geometry.location
                    });
                } else {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
        }

        google.maps.event.addDomListener(window, 'load', initialize);

    </script>
  </head>
  <body>
        <div id="control">
        <p style="font: bold 18px arial; margin-left: 10px"><%=Dirtitle%></p>
        <hr />
        <table style="border-collapse:collapse; margin-top: 6px; margin-bottom: 6px; margin-left: 10px">
            <tr>
                <td style="width: 55px; background-color: lightblue; padding-left: 15px; padding-top: 4px; padding-bottom: 4px">
                    <strong><%=Fromlabel%></strong>
                </td>
                <td style="background-color: lightblue; padding-right: 15px; padding-top: 4px; padding-bottom: 4px">
                    <%=FromSelect%><br />
                    <%=Orlabel%> <input type="text" name="text_from" id="text_from" style="margin-top: 3px" />
                </td>
                <td style="width: 15px"></td>
                <td style="width: 40px; background-color: lightblue; padding-left: 15px; padding-top: 4px; padding-bottom: 4px">
                    <strong><%=Tolabel%></strong>
                </td>
                <td style="background-color: lightblue; padding-right: 15px; padding-top: 4px; padding-bottom: 4px">
                    <%=ToSelect%><br />
                    <%=Orlabel%> <input type="text" name="text_to" id="text_to" style="margin-top: 3px" />
                </td>
                <td style="width: 15px"></td>
                <td>
                    <input name="submit" type="submit" class="newcss3button" value="<%=showdirectionsButton%>" onclick="calcRoute();" />
                </td>
                <td style="padding-left: 10px; padding-right: 10px; text-align: right">
                    <input name="print" type="submit" class="newcss3button" value="<%=PrintButton%>" onclick="window.print()" />
                </td>
            </tr>
        </table>
            
      
      </div>
        <div id="map-canvas"></div>
        <div id="directionsPanel"></div>


  </body>
 
</html>

Open in new window


Thanks for your help,

Peter
0
Comment
Question by:pbissegger
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 35

Accepted Solution

by:
Robert Schutt earned 2000 total points
ID: 39199733
Your function codeAddress() looks fine. I don't see an input (or hidden) with an id of "address" but when I added that (I just saved the html part of your posted code, not the aspx part) and added 2 lines to the function initialize(), it worked fine.
        function initialize() {
            directionsDisplay = new google.maps.DirectionsRenderer();
            var latlng = new google.maps.LatLng(45.5, -73.55);
            var mapOptions = {
                zoom: 7,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                center: latlng
            }
            map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
            directionsDisplay.setMap(map);
            directionsDisplay.setPanel(document.getElementById("directionsPanel"));

            // add these 2 lines
            geocoder = new google.maps.Geocoder();
            codeAddress();
        }

Open in new window

If there is a timing problem (can happen when the map is still loading), you could try changing the codeAddress() call to:
setTimeout(codeAddress, 100);

Open in new window

0
 

Author Closing Comment

by:pbissegger
ID: 39207193
Perfect ! Thanks !
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses

649 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question