Search code examples
javascriptgoogle-mapsgoogle-maps-markersdirections

Google Maps API v3 custom markers not appearing


I want to display on my website something similar to google maps transit directions, so I am trying to display multiple different types of directions on the same map. For exmaple, I want to show a trip where you walk to the bus, take the bus to some other street, and then walk to your final destination.

To do this, I am trying to get the result of multiple directions requests on the same map with custom markers. I have a function called change_map(), which is supposed to display the information for one of these trips on the map.

I have 2 problems:

  1. the markers do not show up on the map.
  2. when fitbounds is un-commented, I get a stack limit exceeded error

I am new to javascript, sorry if my code sucks and thanks for your help!

  var trip_map

  function renderDirections(result) {
    var directionsDisplay = new google.maps.DirectionsRenderer;
    directionsDisplay.setMap(trip_map);
    directionsDisplay.suppressMarkers = true;
    directionsDisplay.setDirections(result);
  } 

  function requestDirections(start, end) {
    var directionsService = new google.maps.DirectionsService;
    directionsService.route({
      origin: start,
      destination: end,
      travelMode: google.maps.DirectionsTravelMode.DRIVING
    }, function(result) {
      renderDirections(result);
    });
  }

  function change_map(pk) {
      var myOptions = {
        center: new google.maps.LatLng(-34.397, 150.644),
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      trip_map = new google.maps.Map(document.getElementById("trip_map"), 
                                     myOptions);

      var bounds = new google.maps.LatLngBounds();       
      for (var j = 0; j < latlngpairs.length; j++) {
      var GPS = new google.maps.LatLng({lat:latlngpairs[0],
                                            lng:latlngpairs[1]});
          var end_marker = new google.maps.Marker({position: GPS, 
                                                   map: trip_map, 
                                                   title: "Hello World!"});
          bounds.extend(end_GPS);
        }
        requestDirections(parts[j], parts[j+1]);
    }
    //trip_map.fitBounds(bounds);
  }

Solution

  • I believe the problem is that you are passing a single object as argument to the constructor of LatLng inside the loop

    Change

    var GPS = new google.maps.LatLng({lat:latlngpairs[0],lng:latlngpairs[1]});
    

    with

    var GPS = new google.maps.LatLng(latlngpairs[0],latlngpairs[1]);
    

    Hope that solves it.