none
Load a different map on another page not working RRS feed

  • Question

  • I have a web app that loads a default map of the current users location. After the user makes some selections on my web page, a list of locations is retrieved from locations that are stored in my SQL database.I have spatial data types and everything set up. The locations name is a hyperlink that when clicked, will take the user to another page with details and directions to the location that they selected. I wrote this function(GetDirectionsMap()) to show a detailed route from the users current location( using latitude, longitude), which I am storing in hiddenfields on the default page, and passing to the searchresults page. The locations latitude and longitude that I get from the database are being stored in hiddenfields from the datareader;

    hdnResponseLat.Value = rdr["Latitude"].ToString();

    hdnResponseLng.Value = rdr["Longitude"].ToString();

    My problem is, whenever I try to run the application, I get a javascript error telling me; Microsoft JScript runtime error: Unable to get value of the property 'value': object is null or undefined

     It is complaing about the hiddenfields on the default page, but, I know that they are not undefined because when I debug the page, they have values?! If I comment out the GetDirectionsMap function, my application works fine. I dont understand why the javascript is bombing out when the searchresponse page hasnt even loaded yet?? Is there an easier way to do this? Any suggestions would be helpful.

           

    var map = null;
    var map2 = null;
    var mapOtions;
    var credentials = "my key";
    var geoLocationProvider;
    var startingZoom = 10;
    var resultsZoom = 4;
    var directionsManager = null;
    
    
    function GetMap() {
        // Set the default page map and view settings
        mapOtions = {
            credentials: credentials,
            mapTypeId: Microsoft.Maps.MapTypeId.road,
            animate: false,
            zoom: startingZoom,
            center: new Microsoft.Maps.Location(geoLocationProvider)
        };
    
        // Initialize the map
        map = new Microsoft.Maps.Map(document.getElementById("myMap"), mapOtions);
    
        geoLocationProvider = new Microsoft.Maps.GeoLocationProvider(map); // Initialize the location provider 
        geoLocationProvider.getCurrentPosition({ successCallback: displayCenter })// Get the user's current location, set as default
        
    
    }
    function displayCenter(args) {
        //Display the users location when the goe location request returns
        //alert("May we use your Location?")
        var locationPoint1 = args.center.latitude;
        var locationPoint2 = args.center.longitude;
        var lat = document.getElementById("hdnLatitude").value = locationPoint1;
        var lng = document.getElementById("hdnLongitude").value = locationPoint2;
        map.entities.clear();
        var pushpin = new Microsoft.Maps.Pushpin(map.getCenter(), {text: '1'});
        map.entities.push(pushpin);
        pushpin.setLocation(new Microsoft.Maps.Location(locationPoint1, locationPoint2));
    
    
    function GetDirectionsMap() {
        // Initialize the map
        map2 = new Microsoft.Maps.Map(document.getElementById("myMap2"), { credentials: credentials });
        Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: createDrivingRoute });
    
        
        }
    function createDrivingRoute()
    {
      //Initialize the directions manager
      directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map2);
      var startlat;
      var startlong;
     
      // Set Route Mode to driving 
      directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.driving });
      var startlat = document.getElementById("hdnLatitude").value;
      var startlong = document.getElementById("hdnLongitude").value;
      var startWaypoint = new Microsoft.Maps.Directions.Waypoint({ location: new Microsoft.Maps.Location(startlat, startlong) });
      directionsManager.addWaypoint(startWaypoint);
      var lat = document.getElementById("hdnResponseLat").value;
      var long = document.getElementById("hdnResponseLng").value;
      var EndWaypoint = new Microsoft.Maps.Directions.Waypoint({ location: new Microsoft.Maps.Location(lat, long) });
      directionsManager.addWaypoint(endWaypoint);
      // Set the element in which the itinerary will be rendered
      directionsManager.setRenderOptions({ itineraryContainer: document.getElementById("directionsItinerary") });
      displayAlert('Calculating directions...');
      directionsManager.calculateDirections();
    }
      if (!directionsManager){
       Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: createDrivingRoute });
     }
     else{
       createDrivingRoute();
     }
        


    mark a fisher


    • Edited by MarkF67 Friday, May 3, 2013 6:39 PM
    Friday, May 3, 2013 6:27 PM

Answers

  • This line of code looks odd:

    var lat = document.getElementById("hdnLatitude").value = locationPoint1;
    var lng = document.getElementById("hdnLongitude").value = locationPoint2;

    Change this to this:

    document.getElementById("hdnLatitude").value = locationPoint1;
    document.getElementById("hdnLongitude").value = locationPoint2;

    Also, in these lines of code:

    var startlat = document.getElementById("hdnLatitude").value;
     
    var startlong = document.getElementById("hdnLongitude").value;
     
    var startWaypoint = new Microsoft.Maps.Directions.Waypoint({ location: new Microsoft.Maps.Location(startlat, startlong) });
      directionsManager
    .addWaypoint(startWaypoint);
     
    var lat = document.getElementById("hdnResponseLat").value;
     
    var long = document.getElementById("hdnResponseLng").value;
     
    var EndWaypoint = new Microsoft.Maps.Directions.Waypoint({ location: new Microsoft.Maps.Location(lat, long) });

    The lat,long, startlat and startlong are strings. You need to trun them into numbers before passing them into the Location object. To do this wrap them with parseFloat()


    http://rbrundritt.wordpress.com

    • Proposed as answer by Ricky_Brundritt Saturday, May 4, 2013 9:24 AM
    • Marked as answer by MarkF67 Saturday, May 4, 2013 11:41 AM
    Saturday, May 4, 2013 9:24 AM
  • Ok, I see the issue. I've got double quotes in the code which should be single quotes. Here is a corrected version.

    Page.ClientScript.RegisterStartupScript(this.GetType(), "GetDirectionsMap", "<script language='javascript'> document.addEventListener('DOMContentLoaded', GetDirectionsMap, false); </script>");


    http://rbrundritt.wordpress.com

    • Marked as answer by MarkF67 Monday, May 13, 2013 4:33 PM
    Monday, May 13, 2013 8:07 AM

All replies

  • This line of code looks odd:

    var lat = document.getElementById("hdnLatitude").value = locationPoint1;
    var lng = document.getElementById("hdnLongitude").value = locationPoint2;

    Change this to this:

    document.getElementById("hdnLatitude").value = locationPoint1;
    document.getElementById("hdnLongitude").value = locationPoint2;

    Also, in these lines of code:

    var startlat = document.getElementById("hdnLatitude").value;
     
    var startlong = document.getElementById("hdnLongitude").value;
     
    var startWaypoint = new Microsoft.Maps.Directions.Waypoint({ location: new Microsoft.Maps.Location(startlat, startlong) });
      directionsManager
    .addWaypoint(startWaypoint);
     
    var lat = document.getElementById("hdnResponseLat").value;
     
    var long = document.getElementById("hdnResponseLng").value;
     
    var EndWaypoint = new Microsoft.Maps.Directions.Waypoint({ location: new Microsoft.Maps.Location(lat, long) });

    The lat,long, startlat and startlong are strings. You need to trun them into numbers before passing them into the Location object. To do this wrap them with parseFloat()


    http://rbrundritt.wordpress.com

    • Proposed as answer by Ricky_Brundritt Saturday, May 4, 2013 9:24 AM
    • Marked as answer by MarkF67 Saturday, May 4, 2013 11:41 AM
    Saturday, May 4, 2013 9:24 AM
  • Richard,

    Thank you for the proposed answer. I have been following your blog for a few months now, it has been great. I have learned a great deal. Do you have a good link for adding multiple pushpins on a map with locations coming from a database? Your direction will be very appreciated.Thank you.


    mark a fisher

    Saturday, May 4, 2013 11:44 AM
  • I changed these lines to;

    var locationPoint1 = args.center.latitude;
    var locationPoint2 = args.center.longitude;
    document.getElementById("hdnLatitude").value = locationPoint1;
    document.getElementById("hdnLongitude").value = locationPoint2;

    I am not certain  how to wrap my other lines; I tried this;

    var startlat = parseFloat(document.getElementById("hdnLatitude").value);
    var startlong = parseFloat(document.getElementById("hdnLongitude").value);

    but it bombs out, where should I start to wrap it??


    mark a fisher

    Tuesday, May 7, 2013 1:54 PM
  • That looks to be correct. Is there an error message being thrown?

    http://rbrundritt.wordpress.com

    Tuesday, May 7, 2013 3:22 PM
  • I tried this too;

    function createDrivingRoute()
    {
      //Initialize the directions manager
      directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map2);
     
      // Set Route Mode to driving 
      directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.driving });
      
          if (document.getElementById("hdnStartingLat") == null || document.getElementById("hdnStartingLng") == null
          || document.getElementById("hdnStartingLat") == "" || document.getElementById("hdnStartingLng") == "") {
    
              document.getElementById("hdnStartingLat").value = "";
              document.getElementById("hdnStartingLng").value = "";
              }
              else{ 
              var startLat = document.getElementById(parseFloat("hdnStartingLat")).value;
              var startLng = document.getElementById(parseFloat("hdnStartingLng")).value;
              var startWaypoint = new Microsoft.Maps.Directions.Waypoint({ location: new Microsoft.Maps.Location(startLat, startLng) });
              directionsManager.addWaypoint(startWaypoint);
              var lat = document.getElementById(parseFloat("hdnResponseLat")).value;
              var lng = document.getElementById(parseFloat("hdnResponseLng")).value;
              var EndWaypoint = new Microsoft.Maps.Directions.Waypoint({ location: new Microsoft.Maps.Location(lat, lng) });
              directionsManager.addWaypoint(endWaypoint);
              // Set the element in which the itinerary will be rendered
              directionsManager.setRenderOptions({ itineraryContainer: document.getElementById("directionsItinerary") });
              displayAlert('Calculating directions...');
              directionsManager.calculateDirections();
          }
      
    }
      if (!directionsManager){
       Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: createDrivingRoute });
     }
     else{
       createDrivingRoute();
     }
        

    My C# code is this:

    I am Geocoding the zipcode entered, and passing this  latitude, longitude result to my database where it will return locations within the desired radius. Then, I am passing the latitude and longitude to another page using Session. 

    protected void btnSearch_Click(object sender, EventArgs e)
        {    //get health centers from database that are near the zip code or address entered into the textbox, in miles selected from the drop down list
            lblLatlng.Text = GeocodeAddress(txtZipCode.Text);
            if (lblLatlng.Text == "")
            {
                return;
            }
            else
            {
                LocationResult coordinates = new LocationResult();
                coordinates.GetCoordinates(lblLatlng.Text);
                lblLat.Text = Convert.ToString(coordinates.Latitude);
                lblLng.Text = Convert.ToString(coordinates.Longitude);
            }
            if (lblLat.Text != "" || lblLng.Text != "")
            {
                var con = new SqlConnection(ConfigurationManager.ConnectionStrings["HealthMappingConnectionString"].ConnectionString);
    
                con.Open();
                try
                {
                    var prcLocationListByGeography = new SqlCommand("prcLocationListByGeography", con);
                    prcLocationListByGeography.CommandType = CommandType.StoredProcedure;
    
                    prcLocationListByGeography.Parameters.AddWithValue("@latitude", Convert.ToDecimal(lblLat.Text));
                    prcLocationListByGeography.Parameters.AddWithValue("@longitude", Convert.ToDecimal(lblLng.Text));
                    prcLocationListByGeography.Parameters.AddWithValue("@radiusMi", ddlDistance.SelectedValue);
    
                    SqlDataAdapter SQLDataAdapter = new SqlDataAdapter(prcLocationListByGeography);
                    DataTable dtResult = new DataTable();
                    SQLDataAdapter.Fill(dtResult);
                    healthCenters.DataSource = dtResult;
                    healthCenters.DataBind();
                    SQLDataAdapter.Dispose();
                    con.Close();
    
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    if (con.State == ConnectionState.Open)
                        con.Close();
                }
    
            }
            Session["latitude"] = Convert.ToDecimal(lblLat.Text);
            Session["longitude"] = Convert.ToDecimal(lblLng.Text);
    
        }
    

    I am then loading the Session Variables on the searchResponse page, and calling my GetDirections function in my page load:

    protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                hdnStartingPoints.Value = Session["latitude"].ToString() + "," + Session["longitude"].ToString();
                hdnStartingLat.Value = Session["latitude"].ToString();
                hdnStartingLng.Value = Session["longitude"].ToString();
                /*Create another .js function for this pages map to show the centers location that was selected from previous page.*/
                Page.ClientScript.RegisterStartupScript(this.GetType(), "GetDirectionsMap", "<script language='javascript'> GetDirectionsMap(); </script>");
            }

    I have a watch set on my variables, they are beinh populated, but my javascript keeps bombing out on the hiddenfields values(Microsoft JScript runtime error: Unable to set value of the property 'value': object is null or undefined) I even tried to set the hiddenfield values with an empty string to see if it will run, with no luck. I need some suggestions.


    mark a fisher

    Tuesday, May 7, 2013 4:16 PM
  • Yes,

     It is saying that the var startlat = parseFloat(document.getElementById("hdnLatitude").value); is undefined. I believe that I am not converting my values completely somewhere. I'm checking now...


    mark a fisher

    Tuesday, May 7, 2013 7:25 PM
  • That error sounds like the parseFloat it failing because the value being passed in is undefined. Is this JavaScript function running on page load? Is it possible it is running before the hdnLatitude object is rendered on the screen?

    http://rbrundritt.wordpress.com

    Wednesday, May 8, 2013 10:46 AM
  • This map is on another page, not the default page, should it still bomb out even if this page is not loaded yet. This page gets loaded after the user makes some choices on the default page. Then, yes, the map is load in the results pages load event: 
    protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                hdnStartingPoints.Value = Session["latitude"].ToString() + "," + Session["longitude"].ToString();
                hdnStartingLat.Value = Session["latitude"].ToString();
                hdnStartingLng.Value = Session["longitude"].ToString();
                /*Create another .js function for this pages map to show the centers location that was selected from previous page.*/
                Page.ClientScript.RegisterStartupScript(this.GetType(), "GetDirectionsMap", "<script language='javascript'> GetDirectionsMap(); </script>");
            }
    I set a few breaks in the debugger and the hidden filelds are getting values. But, the javascript is running on the page that is not even loaded yet. I'm just learning javascript, does it run on every page in my web application, even before it gets requested?

    mark a fisher

    Wednesday, May 8, 2013 1:02 PM
  • Ok, instead of this: Page.ClientScript.RegisterStartupScript(this.GetType(), "GetDirectionsMap", "<script language='javascript'> GetDirectionsMap(); </script>");
    which will run as soon as it is added to the page. Try this instead:

    Page.ClientScript.RegisterStartupScript(this.GetType(), "GetDirectionsMap", "<script language='javascript'> document.addEventListener("DOMContentLoaded", GetDirectionsMap, false); </script>");

    This will add an event listener that waits for the document to be loaded before calling the GetDirectionsMap function.


    http://rbrundritt.wordpress.com

    Wednesday, May 8, 2013 3:52 PM
  • I am getting 4 errors after adding the code you suggested, I tried to format it  different ways too. Is your syntax correct?

    The errors are;

    ) expected

    ; expected

    ; expected

    Invalid expression term ')'

    Here i what you gave me;

    Page.ClientScript.RegisterStartupScript(this.GetType(), "GetDirectionsMap", "<script language='javascript'> document.addEventListener("DOMContentLoaded", GetDirectionsMap, false); </script>");

     


    mark a fisher


    • Edited by MarkF67 Sunday, May 12, 2013 3:23 PM
    Friday, May 10, 2013 6:59 PM
  • Ok, I see the issue. I've got double quotes in the code which should be single quotes. Here is a corrected version.

    Page.ClientScript.RegisterStartupScript(this.GetType(), "GetDirectionsMap", "<script language='javascript'> document.addEventListener('DOMContentLoaded', GetDirectionsMap, false); </script>");


    http://rbrundritt.wordpress.com

    • Marked as answer by MarkF67 Monday, May 13, 2013 4:33 PM
    Monday, May 13, 2013 8:07 AM
  • Thank you, this stopped the errors. My map is still not loading with the directions routed on it? It is loading a map with a global view of the world. I am initializing my map with the code below
    function GetDirectionsMap() {
        // Initialize the map
        map2 = new Microsoft.Maps.Map(document.getElementById("myMap2"), {credentials: credentials});
        Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: directionsModuleLoaded });
     
        }
    
        function directionsModuleLoaded() {
            // Initialize the DirectionsManager
            directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map2);
    
            // Create start and end waypoints
            var endPoint = document.getElementById('hdnResponseLat').value + "," + document.getElementById('hdnResponseLng').value;
            var startWaypoint = new Microsoft.Maps.Directions.Waypoint({ point: document.getElementById('hdnStartingPoints').value });
            var endWaypoint = new Microsoft.Maps.Directions.Waypoint({ point: endPoint });
    
            directionsManager.addWaypoint(startWaypoint);
            directionsManager.addWaypoint(endWaypoint);
    
            // Set request options
            directionsManager.setRequestOptions({ avoidTraffic: true, routeOptimization: Microsoft.Maps.Directions.RouteOptimization.shortestDistance });
    
            // Set the render options
            directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('directionsItinerary') });
    
            // Specify a handler for when an error occurs
            Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', displayError);
    
            // Calculate directions, which displays a route on the map
            directionsManager.calculateDirections();
    
        }
    You have been very helpful thus far. I am not sure if it is better to use the RouteService and its CalculateRouteRequest() method, or to use the AJAXControlv7 REST Services to get route directions?? What way is better?

    mark a fisher

    Monday, May 13, 2013 4:47 PM
  • Hi Richard,

    After some searching I found a solution: I went to; http://msdn.microsoft.com/en-us/library/gg427607.aspx

    And I found this function to help me. I did not have to use the parseFloat() method to convert my hiddenFields before passing them to the Routes REST Service, it worked fine, even when I concantanated the values of two hiddenFields.  I would like to know the correct link(if you know it off hand) to the directionsItinerary module, so that I can put directions on my page. Are you familiar with this? Here are the working functions to display a map with directions from a starting point to an ending point:

    function GetDirectionsMap() {
    
        // Initialize the map
        map2 = new Microsoft.Maps.Map(document.getElementById("myMap2"), { credentials: credentials, mapTypeId: Microsoft.Maps.MapTypeId.road });
        map2.getCredentials(MakeRouteRequest);
    
        }
    
        function MakeRouteRequest() {
            var routeRequest = "http://dev.virtualearth.net/REST/v1/Routes?wp.0=" + document.getElementById('hdnStartingPoints').value + "&wp.1=" +
            document.getElementById('hdnEndingPoints').value + "&routePathOutput=Points&output=json&jsonp=RouteCallback&key=" + credentials;
            CallRestService(routeRequest);
        }
        function RouteCallback(result) {
            if (result &&
                       result.resourceSets &&
                       result.resourceSets.length > 0 &&
                       result.resourceSets[0].resources &&
                       result.resourceSets[0].resources.length > 0) {
                // Set the map view
                var bbox = result.resourceSets[0].resources[0].bbox;
                var viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(bbox[0], bbox[1]), new Microsoft.Maps.Location(bbox[2], bbox[3]));
                map2.setView({ bounds: viewBoundaries });
                // Draw the route
                var routeline = result.resourceSets[0].resources[0].routePath.line;
                var routepoints = new Array();
    
                for (var i = 0; i < routeline.coordinates.length; i++) {
    
                    routepoints[i] = new Microsoft.Maps.Location(routeline.coordinates[i][0], routeline.coordinates[i][1]);
                }
    
    
                // Draw the route on the map
                var routeshape = new Microsoft.Maps.Polyline(routepoints, { strokeColor: new Microsoft.Maps.Color(200, 0, 0, 200) });
                map2.entities.push(routeshape);
    
            }
    
    
    
        }


    mark a fisher

    Monday, May 13, 2013 5:57 PM
  • Hi Richard,

    You provided this solution to me last month because my map wasnt loading on postbacks, since the DOM wasnt fully loaded yet.:

    Page.ClientScript.RegisterStartupScript(this.GetType(), "GetDirectionsMap", "<script language='javascript'> document.addEventListener('DOMContentLoaded', GetDirectionsMap, false); </script>");

    This script works fine in development. I deployed my app to test today and after running it in IE9, I am getting an error on the "document.addEventListener".

    The error is:

    Error: Object doesn't support property or method 'addEventListener'
    Do you have any insight on this? Thank you.


    mark a fisher

    Wednesday, June 5, 2013 4:42 PM
  • Looks like a cross browser issue with attaching events. Here is a modified version:

    Page.ClientScript.RegisterStartupScript(this.GetType(), "GetDirectionsMap", "<script language='javascript'>(document.addEventListener) ? document.addEventListener('DOMContentLoaded', GetDirectionsMap, false) : document.attachEvent('readystatechange', GetDirectionsMap);</script>");


    http://rbrundritt.wordpress.com

    Wednesday, June 5, 2013 7:16 PM
  • I made this change, my map is not showing at all now, but I am not getting the errors, In IE9.

    function GetMap() {
        mapOtions = {
            credentials: credentials
            //mapTypeId:Microsoft.Maps.MapTypeId.road,
            //animate: false
    
        };
    
        // Initialize the map
        map = new Microsoft.Maps.Map(document.getElementById("myMap"), mapOtions);
    
        //Set the default page map and view settings
        var lat = document.getElementById("hdnLatitude").value;
        var lng = document.getElementById("hdnLongitude").value;
        
        //set the maps view with the users location
        map.setView({ credentials: credentials, zoom: 12, center: new Microsoft.Maps.Location(lat, lng) });
        map.entities.clear();
        var pushpin = new Microsoft.Maps.Pushpin(map.getCenter(lat, lng), { text: '1' });
        map.entities.push(pushpin);
        pushpin.setLocation(new Microsoft.Maps.Location(lat, lng));
       
    
    }
    

    Also a dialog box pops up telling me that "Only secure content is displayed" with an option to display all content. Could this dialog box be interfering with my map loading, and that is why I'm having the issue? My web server is set to display intranet sites in Compatibility mode, could this be an issue as well?


    mark a fisher

    Thursday, June 6, 2013 2:25 PM
  • Hi Rich,

    In IE, I keep getting this error when trying to load my map for the first time on my page. My map is loading with the users location. The location info is coming from my database. I am getting an error on this new modified script that you suggested to me.

    Page.ClientScript.RegisterStartupScript(this.GetType(), "GetDirectionsMap", "<script language='javascript'>(document.addEventListener) ? document.addEventListener('DOMContentLoaded', GetDirectionsMap, false) : document.attachEvent('readystatechange', GetDirectionsMap);</script>");

    The error is saying the object doesnt support this property or method. This is not happening in Firefox or Chrome. I have been trying to figure this out with no luck. Can you suggest anything to me? This is my get map function:

    function GetMap() {
        mapOtions = {
            credentials: credentials,
            //mapTypeId:Microsoft.Maps.MapTypeId.road,
            animate: false
    
        };
    
        // Initialize the map
        map = new Microsoft.Maps.Map(document.getElementById("myMap"), mapOtions);
    
        //Set the default page map and view settings
        var lat = document.getElementById("hdnLatitude").value;
        var lng = document.getElementById("hdnLongitude").value;
        
        //set the maps view with the users location
        map.setView({ credentials: credentials, zoom: 12, center: new Microsoft.Maps.Location(lat, lng) });
        map.entities.clear();
        var pushpin = new Microsoft.Maps.Pushpin(map.getCenter(lat, lng), { text: '1' });
        map.entities.push(pushpin);
        pushpin.setLocation(new Microsoft.Maps.Location(lat, lng));
    
    }

     


    mark a fisher

    Monday, June 10, 2013 5:13 PM