2017-02-08 134 views
0

我一直在研究Google Maps API,以創建一個網站,用於將用戶地理定位並向附近的開放式/封閉式咖啡館顯示它們。JS - Google Maps API - 標記方向單擊

我目前正試圖整合功能,使用戶指示從他們當前的地理位置到咖啡館點擊標記時,但我無法獲得此工作,並想知道如果有人可以提供任何指示如何實現這一點

var service, map, pos, infoWindow, google, directionsService, directionsDisplay; 


/* create google map & add styling */ 
function initMap() { 

    clicked = null; 

    directionsService = new google.maps.DirectionsService; 
    directionsDisplay = new google.maps.DirectionsRenderer({ 
     suppressMarkers: true, 
     suppressBicyclingLayer: true 
    }); 
    directionsDisplay.setMap(map); 

    var styledMapType = new google.maps.StyledMapType([{"featureType": "all", "elementType": "geometry.fill", "stylers": [{"weight": "2.00"}]}, {"featureType": "all", "elementType": "geometry.stroke", "stylers": [{"color": "#9c9c9c"}]}, {"featureType": "all", "elementType": "labels.text", "stylers": [{"visibility": "on"}]}, {"featureType": "administrative.locality", "elementType": "labels.text.fill", "stylers": [{"color": "#ac8d93"}]}, {"featureType": "landscape", "elementType": "all", "stylers": [{"color": "#f2f2f2"}]}, {"featureType": "landscape", "elementType": "geometry.fill", "stylers": [{"color": "#ffffff"}]}, {"featureType": "landscape.man_made", "elementType": "geometry.fill", "stylers": [{"color": "#ffffff"}]}, {"featureType": "poi", "elementType": "all", "stylers": [{"visibility": "off"}]}, {"featureType": "road", "elementType": "all", "stylers": [{"saturation": -100}, {"lightness": 45}]}, {"featureType": "road", "elementType": "geometry.fill", "stylers": [{"color": "#eeeeee"}]}, {"featureType": "road", "elementType": "labels.text.fill", "stylers": [{"color": "#7b7b7b"}]}, {"featureType": "road", "elementType": "labels.text.stroke", "stylers": [{"color": "#ffffff"}]}, {"featureType": "road.highway", "elementType": "all", "stylers": [{"visibility": "simplified"}]}, {"featureType": "road.arterial", "elementType": "labels.icon", "stylers": [{"visibility": "off"}]}, {"featureType": "transit", "elementType": "all", "stylers": [{"visibility": "off"}]}, {"featureType": "water", "elementType": "all", "stylers": [{"color": "#46bcec"}, {"visibility": "on"}]}, {"featureType": "water", "elementType": "geometry.fill", "stylers": [{"color": "#c8d7d4"}]}, {"featureType": "water", "elementType": "labels.text.fill", "stylers": [{"color": "#070707"}]}, {"featureType": "water", "elementType": "labels.text.stroke", "stylers": [{"color": "#ffffff"}]}], 
      {name: 'Styled Map'}); 
    var chch = {lat: -43.530, lng: 172.646}; 
    map = new google.maps.Map(document.getElementById('map'), { 
     center: chch, 
     zoom: 13, 
     mapTypeControlOptions: { 
      mapTypeIds: ['roadmap', 'satellite', 'hybrid', 'terrain', 
       'styled_map'] 
     } 
    }); 
    map.mapTypes.set('styled_map', styledMapType); 
    map.setMapTypeId('styled_map'); 



    infoWindow = new google.maps.InfoWindow({map: map}); 

    service = new google.maps.places.PlacesService(map); 
    service.nearbySearch({ 
     location: chch, 
     openNow: true && false, 
     radius: 5000, 
     type: ['cafe'] 
    }, function (results, status) { 
     if (status === google.maps.places.PlacesServiceStatus.OK) { 
      for (var i = 0; i < results.length; i++) { 
       createMarker(results[i]); 
      } 
     } 
    }); 

    geolocate(); 
    initAutocomplete(); 

} 


function createMarker(place) { 
    var marker = new google.maps.Marker({ 
     map: map, 
     icon: 'img/greenmarker.svg', 
     position: place.geometry.location 
    }); 
    var request = { 
     reference: place.reference 
    }; 

    service.getDetails(request, function (place, status) { 
     var open = ""; 

     if (!place.hasOwnProperty('opening_hours')) { 
      open += "No open times provided"; 
      marker.setIcon('img/greymarker.svg'); 
     } else if (place.opening_hours.open_now === true) { 
      open += "We are Open"; 
     } else { 
      open += "We are Closed"; 
      marker.setIcon('img/redmarker.svg'); 
     } 
     ; 


     if (status === google.maps.places.PlacesServiceStatus.OK) { 
      var contentStr = '<h5>' + place.name + '</h5><p>' + place.formatted_address; 
      if (!!place) 
       contentStr += '<br>' + open; 

      if (!!place.formatted_phone_number) 
       contentStr += '<br>' + place.formatted_phone_number; 
      if (!!place.website) 
       contentStr += '<br><a target="_blank" href="' + place.website + '">' + place.website + '</a></p>'; 
     } else { 
      var contentStr = "<h5>No Result, status=" + status + "</h5>"; 
     } 
     setupInfowindow(marker, infoWindow, contentStr); 

    }); 

    function setupInfowindow(marker, infoWindow, contentStr) { 
     marker.addListener('click', function() { 
      infoWindow.setContent(contentStr); 
      infoWindow.open(map, this); 
     }); 
    } 

    google.maps.event.addListener(marker, 'click', function() { 
     clicked = marker.getPosition(); 
     calculateAndDisplayRoute(directionsService, directionsDisplay, pos, clicked); 
     console.log(clicked); 

//  clicked = { 
//   lat: this.position.lat(), 
//   lng: this.position.lng() 
//  }; 
    }); 
} 


function geolocate() { 
    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(function (position) { 

      pos = { 
       lat: position.coords.latitude, 
       lng: position.coords.longitude 
      }; 
      new google.maps.Marker({ 
       map: map, 
       icon: 'img/cross.svg', 
       position: pos 
      }); 

      infoWindow.setPosition(pos); 
      infoWindow.setContent('Location found.'); 

      map.setCenter(pos); 
      map.setZoom(14); 
     }, function() { 
      handleLocationError(true, infoWindow, map.getCenter()); 
     }); 
    } else { 
     // Browser doesn't support Geolocation 
     handleLocationError(false, infoWindow, map.getCenter()); 
    } 
} 



function initAutocomplete() { 

    // Create the search box and link it to the UI element. 
    var input = document.getElementById('pac-input'); 
    var searchBox = new google.maps.places.SearchBox(input); 
    //map.controls[google.maps.ControlPosition.TOP_LEFT].push(input); 

    // Bias the SearchBox results towards current map's viewport. 
    map.addListener('bounds_changed', function() { 
     searchBox.setBounds(map.getBounds()); 
    }); 

    var markers = []; 
    // Listen for the event fired when the user selects a prediction and retrieve 
    // more details for that place. 
    searchBox.addListener('places_changed', function() { 
     var places = searchBox.getPlaces(); 

     if (places.length === 0) { 
      return; 
     } 

     // Clear out the old markers. 
     markers.forEach(function (marker) { 
      marker.setMap(null); 
     }); 
     markers = []; 

     // For each place, get the icon, name and location. 
     var bounds = new google.maps.LatLngBounds(); 
     places.forEach(function (place) { 
      if (!place.geometry) { 
       console.log("Returned place contains no geometry"); 
       return; 
      } 

      var searched = { 
       lat: place.geometry.location.lat(), 
       lng: place.geometry.location.lng() 
      }; 

      infoWindow.setPosition(searched); 
      infoWindow.setContent('Location found.'); 
      map.setCenter(searched); 
      map.setZoom(14); 

      // Create a marker for each place. 
      markers.push(new google.maps.Marker({ 
       map: map, 
       icon: 'img/cross.svg', 
       title: place.name, 
       position: place.geometry.location 
      })); 


      if (place.geometry.viewport) { 
       // Only geocodes have viewport. 
       bounds.union(place.geometry.viewport); 
      } else { 
       bounds.extend(place.geometry.location); 
      } 
     }); 
    }); 
} 


function calculateAndDisplayRoute(directionsService, directionsDisplay, pos, clicked) { 
    directionsService.route({ 
     origin: pos, 
     destination: clicked, 
     travelMode: 'BICYCLING' 
    }, function (response, status) { 
     if (status === 'OK') { 
      directionsDisplay.setDirections(response); 
     } else { 
      window.alert('Directions request failed due to ' + status); 
     } 
    }); 
} 



//if browser doesn't have geolocation then search box shows 
function handleLocationError() { 
    $(".input__wrapper").show(); 
} 

here's a link that shows where i'm currently at with this - (在這個例子的目的,我已經編輯了地理定位功能,使得它重定向到網吧正在從收集的城市)

任何幫助,將不勝感激!

回答

0

兩件事情阻止你的工作提供的代碼:

  1. 你改變了地理位置的發現在var chch一個靜態的位置,所以var pos從未設置過
  2. 您NAVER附directionsDisplay任何面板。我加

    <div id="directionsPanel"></div> 
    

    的標記和

    directionsDisplay.setPanel(document.getElementById("directionsPanel")); 
    

    .setMap()呼叫

而且事實證明,除此之外,你的代碼已經正確後,換來的只是不在任何地方顯示: https://jsfiddle.net/786zeqc7/4/ (您必須使用滾動條滾動輸出窗口,因爲ma p覆蓋整個框架,以瞭解用戶在點擊一個標記後,在地圖容器下方的方向) 看到一個漂亮的業餘列布局此更新搗鼓預覽的目的:https://jsfiddle.net/786zeqc7/5/

一些建議,超越了一個問題:

  1. 您應該檢查status === google.maps.DirectionsStatus.OK而不是'OK' - 這是不太可能的,但是當API應該更改該常量的值時,它會破壞您的代碼。

  2. 有一些更多的JavaScript錯誤控制檯拋出,你應該考慮和解決

  3. 使用protocoll少網址標記圖像,使它們在HTTPS環境中工作以及

  4. 你在全局範圍內有var pos以及函數calculateAndDisplayRoute()的一個參數 - 這讓我困惑,而且在幾個月或幾年內再次查看此代碼時,它可能會使你感到困惑。

+0

哎@Connum,非常感謝您的幫助!恐怕我原來的帖子中可能沒有正確解釋自己 - 我不是想要獲得書面指示,而是用戶和點擊標記之間的藍色多段線方向 –

+0

好吧......所以,我找不到默認顯示路由的原因,雖然它在這個例子中工作:http://jsfiddle.net/user2314737/u9no8te4/我只是無法找到任何區別。 但是,我已經能夠根據此問題的建議顯示路線:http://stackoverflow.com/questions/16180104/get-a-polyline-from-google-maps-directions-v3 請參閱https: //jsfiddle.net/786zeqc7/9/(你可能需要再次點擊「運行」,這似乎是jsfiddle環境中的地圖問題) – Connum