Question

I have a map that gives directions based on geolocation, however I want a marker to be on the map even before the user gets directions. I can't seem to get the marker to show up when the webpage loads. The code I am using is as follows:

<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>

var directionDisplay, map;
  function calculateRoute(from, to) {
    // Center initialized to Lafayette IN
    var travelMode = $('input[name="travelMode"]:checked').val();
    var myOptions = {
      zoom: 10,
      center: new google.maps.LatLng(40.40541,-86.89048),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var panel = document.getElementById("directionsPanel");
    var marker = new google.maps.Marker({
    position: new google.maps.LatLng(40.40541,-86.89048), 
    map: map,
    title: "Beyond the Box"
  }); 
     marker.setMap(map);
    // Draw the map
    var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);

    var directionsService = new google.maps.DirectionsService();
    var directionsRequest = {
      origin: from,
      destination: to,
      travelMode: google.maps.DirectionsTravelMode[travelMode],
      unitSystem: google.maps.UnitSystem.IMPERIAL
    };
    directionsService.route(
      directionsRequest,
      function(response, status)
      {
        if (status == google.maps.DirectionsStatus.OK)
        {
          new google.maps.DirectionsRenderer({
            map: mapObject,
            directions: response,
          });
        }
        if (status == google.maps.DirectionsStatus.OK)
        {
          directionsDisplay = new google.maps.DirectionsRenderer({
            map: mapObject,
            directions: response,
          });
          directionsDisplay.setPanel(panel);
        }
        else
          $("#error").append("Unable to retrieve your route<br />");
      }
    );
   }

   $(document).ready(function() {
    // If the browser supports the Geolocation API
    if (typeof navigator.geolocation == "undefined") {
      $("#error").text("Your browser doesn't support the Geolocation API");
      return;
    }

    $("#from-link, #to-link").click(function(event) {
      event.preventDefault();
      var addressId = this.id.substring(0, this.id.indexOf("-"));

      navigator.geolocation.getCurrentPosition(function(position) {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({
          "location": new google.maps.LatLng(position.coords.latitude,     position.coords.longitude)
        },
        function(results, status) {
          if (status == google.maps.GeocoderStatus.OK)
            $("#" + addressId).val(results[0].formatted_address);
          else
            $("#error").append("Unable to retrieve your address<br />");
        });
      },
      function(positionError){
        $("#error").append("Error: " + positionError.message + "<br />");
      },
      {
        enableHighAccuracy: true,
        timeout: 10 * 1000 // 10 seconds
      });
    });

    $("#calculate-route").submit(function(event) {
      event.preventDefault();
      calculateRoute($("#from").val(), $("#to").val());
    });
  });
  google.maps.event.addDomListener(window, 'load', initialize);

  </script>
</head>
<body>
<body onLoad="calculateRoute()">
<!-- Start Header -->
<?php include("header.php"); ?> 
<!-- End Header -->
Was it helpful?

Solution

You didn't initialize "map" variable. Try this.

var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
marker.setMap(mapObject);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top