Solved

Need Google maps geocoding to center map on initialize

Posted on 2013-05-25
2
315 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
2 Comments
 
LVL 35

Accepted Solution

by:
Robert Schutt earned 500 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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How to use embargo Date/time in php 29 39
Else condition 9 19
Jquery Validation Messages Not Showing Up 3 16
Create an automated page index 9 19
In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

832 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