Google Map API Destination Service

Hi,

I am using the Google Map API v3 to allow users to type their address and get a route plan to their destination. I have it working ok but when the map first loads up before the user has inserted their address i want a marker to appear on the Map for the destination. Their is only one destination so i pull that from my database. I have added the javascript code to insert a marker but it doesnt seem to be doing anything. Anyone know where i am going wrong with it?

<script type="text/javascript">
	var directionsDisplay;
	var directionsService = new google.maps.DirectionsService();
	var map;
	var marker;

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var farmer_location = new google.maps.LatLng(<?php echo $farm_location_x; ?>,<?php echo $farm_location_y; ?>);
  var mapOptions = {
    zoom:8,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: farmer_location,
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  directionsDisplay.setMap(map);
}

  var marker = new google.maps.Marker({
      position: farmer_location,
      map: map,
      title:"Hello World!"
  });

function calcRoute() {
  var start = document.getElementById("start").value;
  var end = '<?php echo $farm_location_x; ?>,<?php echo $farm_location_y; ?>';
  var request = {
    origin:start,
    destination:end,
    travelMode: google.maps.TravelMode.DRIVING
  };
  directionsService.route(request, function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(result);
    }
  });
}
</script>

Thanks

Hi,

I’d expect that to throw errors because you’ve defined the farmer_location variable in the initialize function and tried to use it outside the function. Make sure you’ve got a javascript console so you can see errors and track them down.

Putting the marker in here and calling setMap on it should work.


function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var farmer_location = new google.maps.LatLng(<?php echo $farm_location_x; ?>,<?php echo $farm_location_y; ?>);
  var mapOptions = {
    zoom:8,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: farmer_location,
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  
  var marker = new google.maps.Marker({
    position: farmer_location,
    map: map,
    title:"Hello World!"
  });

  marker.setMap(map);

}

Ahhh yes. Thanks!