I'm trying to make Google Maps directions work with geolocation (using samples provided by Google Maps). Alone both work, but when combined there is a problem, that the map won't show the path (however autocomplete works fine).
function initMap() {
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat:position.coords.latitude, lng:position.coords.longitude},
zoom: 10
});
var panorama = new google.maps.StreetViewPanorama(
document.getElementById('pano'), {
position: {lat:position.coords.latitude, lng:position.coords.longitude},
pov: {
heading: 34,
pitch: 10
}
});
var usermarker = new google.maps.Marker({
position: {lat:position.coords.latitude, lng:position.coords.longitude},
draggable: true,
map: map,
icon: 'http://x3.cdn03.imgwykop.pl/c3201142/comment_aBtolaUIxKS7cvUnii43PWDPT3Lqduc2,w400.jpg',
});
// test marker
var marker2 = new google.maps.Marker({
position: {lat:50.671064, lng:17.926138},
draggable: true,
map: map,
icon: 'http://emojipedia-us.s3.amazonaws.com/cache/1e/4d/1e4d8093e7011575d9266598a06d8ecb.png',
});
});
new AutocompleteDirectionsHandler(map);
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'WALKING';
var originInput = document.getElementById('origin-input');
var destinationInput = document.getElementById('destination-input');
var modeSelector = document.getElementById('mode-selector');
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsDisplay.setMap(map);
var originAutocomplete = new google.maps.places.Autocomplete(
originInput, {placeIdOnly: true});
var destinationAutocomplete = new google.maps.places.Autocomplete(
destinationInput, {placeIdOnly: true});
this.setupClickListener('changemode-walking', 'WALKING');
this.setupClickListener('changemode-transit', 'TRANSIT');
this.setupClickListener('changemode-driving', 'DRIVING');
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(originInput);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(destinationInput);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(modeSelector);
}
//everything works until this moment
AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
var radioButton = document.getElementById(id);
var me = this;
radioButton.addEventListener('click', function() {
me.travelMode = mode;
me.route();
});
};
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.place_id) {
window.alert("Please select an option from the dropdown list.");
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {'placeId': this.originPlaceId},
destination: {'placeId': this.destinationPlaceId},
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
// map.setStreetView(panorama);
});
};
}
I've experimented with putting the path making part in various positions and finaly got it working. #Jaromanda X - thanks for the idea :)
function initMap() {
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat:position.coords.latitude, lng:position.coords.longitude},
zoom: 10
});
var marker2 = new google.maps.Marker({
position: {lat:50.671064, lng:17.926138},
draggable: true,
map: map,
icon: 'http://emojipedia-us.s3.amazonaws.com/cache/1e/4d/1e4d8093e7011575d9266598a06d8ecb.png',
});
var panorama = new google.maps.StreetViewPanorama(
document.getElementById('pano'), {
position: {lat:position.coords.latitude, lng:position.coords.longitude},
pov: {
heading: 34,
pitch: 10
}
});
var usermarker = new google.maps.Marker({
position: {lat:position.coords.latitude, lng:position.coords.longitude},
draggable: true,
map: map,
icon: 'http://x3.cdn03.imgwykop.pl/c3201142/comment_aBtolaUIxKS7cvUnii43PWDPT3Lqduc2,w400.jpg',
});
new AutocompleteDirectionsHandler(map);
});
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'WALKING';
var originInput = document.getElementById('origin-input');
var destinationInput = document.getElementById('destination-input');
var modeSelector = document.getElementById('mode-selector');
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsDisplay.setMap(map);
var originAutocomplete = new google.maps.places.Autocomplete(
originInput, {placeIdOnly: true});
var destinationAutocomplete = new google.maps.places.Autocomplete(
destinationInput, {placeIdOnly: true});
this.setupClickListener('changemode-walking', 'WALKING');
this.setupClickListener('changemode-transit', 'TRANSIT');
this.setupClickListener('changemode-driving', 'DRIVING');
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(originInput);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(destinationInput);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(modeSelector);
}
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
var radioButton = document.getElementById(id);
var me = this;
radioButton.addEventListener('click', function() {
me.travelMode = mode;
me.route();
});
};
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.place_id) {
window.alert("Please select an option from the dropdown list.");
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {'placeId': this.originPlaceId},
destination: {'placeId': this.destinationPlaceId},
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
map.setStreetView(panorama);
});
};
}
}
Related
I have error with google map when it put Marker it get this error
I do not know what the error is when I click on save it outputs that the data is field is required. in the map it selects the place but when I click on the place this error comes out at the bottom
VM951 livewire.js:13 Uncaught TypeError: Cannot read properties of undefined (reading '$wire')
at Livewire.value (VM951 livewire.js:13:145634)
at placeMarkerAndPanTo (make:2811:27)
at make:2792:11
at geocoder.js:6:1385
at geocoder.js:3:420
at bza (geocoder.js:2:218)
at gia.e [as m] (geocoder.js:3:339)
at Object.c [as _yj5gms] (common.js:123:253)
at GeocodeService.Search?5m2&1d24.745676471010597&2d46.7278229712639&9sen-US&callback=_xdc_._yj5gms&key=AIzaSyDy4tKkS30XU9DJsUA5cqLzg-jtynKS18s&token=45746:1:28
I do not know what the error is when I click on save it outputs that the data is field is required. in the map it selects the place but when I click on the place this error comes out at
this is my code
#section('scripts')
<script src="https://maps.googleapis.com/maps/api/js?key={{env("GOOGLE_KEY")}}&libraries=places&v=weekly"> </script>
<script src="{{ asset('dashboard/assets/js/pages/crud/forms/widgets/select2.js') }}"></script>
<script>
$(document).ready(function() {
$('#kt_select2_3').select2({
placeholder: '',
}).on('change', function() {
#this.properties = $(this).val();
});
});
function mapLocation() {
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var lat, lng;
var markers = [];
var gmarkers = [];
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var riyad = new google.maps.LatLng(24.729518, 46.723341);
var mapOptions = {
zoom: 13,
center: riyad,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
map.addListener('click', function(e) {
var geocoder = geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': e.latLng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//alert(results[1].formatted_address);
if (results[1]) {
//results = results[1];
//var result12 = results[1].formatted_address;
// //document.getElementById("address_pickUp").innerHTML = results[1].formatted_address;
// // alert(document.getElementById("address_pickUp").innerHTML.length)
// if(document.getElementById("address_pickUp").innerHTML.length == 0){
// document.getElementById("address_pickUp").innerHTML = results[1].formatted_address;
// }else{
// document.getElementById("address_dropOff").innerHTML = results[1].formatted_address;
// }
//#this.address = results[1].formatted_address;
// alert("Location: " + results[1].formatted_address + "\r\nLatitude: " + e.latLng.lat() + "\r\nLongitude: " + e.latLng.lng());
//alert(result12);
}
}
placeMarkerAndPanTo(e.latLng, map, results[1].formatted_address);
});
});
var marker = new google.maps.Marker({
// position: markers[0],
position: markers,
map: map
});
function placeMarkerAndPanTo(latLng, map, results) {
if (document.getElementById("pickup_lat").value.length == 0) {
document.getElementById("pickup_lat").value = latLng.lat();
document.getElementById("pickup_lng").value = latLng.lng();
document.getElementById("address_pickUp").value = results;
marker.setPosition(latLng);
map.panTo(latLng);
#this.pickup_lat = latLng.lat();
#this.pickup_lng = latLng.lng();
} else {
document.getElementById("dropoff_lat").value = latLng.lat();
document.getElementById("dropoff_lng").value = latLng.lng();
document.getElementById("address_dropOff").value = results;
marker.setPosition(latLng);
map.panTo(latLng);
#this.dropoff_lat = latLng.lat();
#this.dropoff_lng = latLng.lng();
}
}
directionsDisplay.setMap(map);
google.maps.event.addDomListener(document.getElementById('routebtn'), 'click', calcRoute);
// 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 = [];
// [START region_getplaces]
// 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) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
console.log("latitude: " + place.geometry.location.lat() + ", longitude: " + place.geometry.location.lng());
/*if (document.getElementById("pickup_lat").value.length == 0) {
document.getElementById("pickup_lat").value = place.geometry.location.lat();
document.getElementById("pickup_lng").value = place.geometry.location.lng();
// marker.setPosition(latLng);
// map.panTo(latLng);
//#this.pickup_lat = place.geometry.location.lat();
//#this.pickup_lng = place.geometry.location.lng();
} else {
document.getElementById("dropoff_lat").value = place.geometry.location.lat();
document.getElementById("dropoff_lng").value = place.geometry.location.lng();
}*/
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
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);
}
});
map.fitBounds(bounds);
});
}
#endsection
make-trip.blade.php
<div class="col-lg-12" wire:ignore>
<div class="col-lg-3">
<x-input type="text" field="map" style="margin: 10px; z-index: 0; position: absolute; cursor: pointer; left: 0px; top: 0px;width:350px" placeholder="Search Box" id="pac-input"></x-input>
</div>
I do no now what is the error
I have this project with Google Maps API. Everything works perfectly except that Google Marker added through an input value is not showing. I have inputs, of which two are origin and destination respectively, with direction both show perfectly but the third input which is added later doesn't show. I have a different function to take care of it though.
<input type="text" class="form-control" id="origin_input" name="origin_input">
<input type="text" class="form-control" id="destination_input" name="destination_input">
<input type="text" class="form-control" id="stopOver">
And here is my JavaScript for the Google Map:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {
lat: 7.946527,
lng: -1.023194
},
zoom: 8
});
new AutocompleteDirectionsHandler(map);
addStopOverMarker(map);
}
function addStopOverMarker(map) {
this.map = map;
var stopOver = new google.maps.places.Autocomplete(document.getElementById('stopOver'));
google.maps.event.addListener(stopOver, 'place_changed', function() {
var coord = stopOver.getPlace().geometry.location;
console.log(coord);
window.post = coord;
});
var marker = new google.maps.Marker({
position: window.post,
icon: 'https://png.icons8.com/color/50/000000/street-view.png',
map: map,
draggable: true,
visible: true
});
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'DRIVING';
var originInput = document.getElementById('origin_input');
var destinationInput = document.getElementById('destination_input');
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
// this.service = new google.maps.DistanceMatrixService;
this.directionsDisplay.setMap(map);
var originAutocomplete = new google.maps.places.Autocomplete(
originInput, {
placeIdOnly: true
});
var destinationAutocomplete = new google.maps.places.Autocomplete(
destinationInput, {
placeIdOnly: true
});
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
}
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.place_id) {
window.alert("Please select an option from the dropdown list.");
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {
'placeId': this.originPlaceId
},
destination: {
'placeId': this.destinationPlaceId
},
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
You have three issues with your addStopover function:
you are using the wrong map variable
the icon doesn't exists
you are creating the marker before the place_changed event fires and it's callback function runs
working version of the function:
function addStopOverMarker(map) {
var stopOver = new google.maps.places.Autocomplete(document.getElementById('stopOver'));
google.maps.event.addListener(stopOver, 'place_changed', function() {
var coord = stopOver.getPlace().geometry.location;
console.log(coord);
var marker = new google.maps.Marker({
position: coord,
map: map,
draggable: true,
visible: true
});
});
}
proof of concept fiddle
code snippet:
html,
body,
#map {
height: 90%;
width: 100%;
margin: 0px;
padding: 0px;
}
<div id="map"></div>
<input id="origin_input" value="Tecmiman" />
<input id="destination_input" value="Kumasi" />
<input id="stopOver" value="Bechem" />
<script>
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {
lat: 7.946527,
lng: -1.023194
},
zoom: 8
});
new AutocompleteDirectionsHandler(map);
addStopOverMarker(map);
}
function addStopOverMarker(map) {
var stopOver = new google.maps.places.Autocomplete(document.getElementById('stopOver'));
google.maps.event.addListener(stopOver, 'place_changed', function() {
var coord = stopOver.getPlace().geometry.location;
console.log(coord);
var marker = new google.maps.Marker({
position: coord,
map: map,
draggable: true,
visible: true
});
});
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'DRIVING';
var originInput = document.getElementById('origin_input');
var destinationInput = document.getElementById('destination_input');
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
// this.service = new google.maps.DistanceMatrixService;
this.directionsDisplay.setMap(map);
var originAutocomplete = new google.maps.places.Autocomplete(
originInput, {
placeIdOnly: true
});
var destinationAutocomplete = new google.maps.places.Autocomplete(
destinationInput, {
placeIdOnly: true
});
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
}
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.place_id) {
window.alert("Please select an option from the dropdown list.");
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {
'placeId': this.originPlaceId
},
destination: {
'placeId': this.destinationPlaceId
},
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
</script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap"></script>
How to combine the DirectionsService and PlacesService in google map. I will inspire on this path http://www.indiaproperty.com/godrej-palm-grove-in-poonamallee-chennai-pl4110632?fr=sres2 . I can't get the duration & distance of each location. I need to find each location distance and duration. I given the code below:
var map;
var infowindow;
var markersArray = [];
var pyrmont = new google.maps.LatLng(20.268455824834792, 85.84099235520011);
var marker;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
var places = [];
// var waypoints = [];
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 14,
zoomControl: false,
scaleControl: false,
scrollwheel: false,
disableDoubleClickZoom: true,
});
infowindow = new google.maps.InfoWindow();
//document.getElementById('directionsPanel').innerHTML='';
search_types();
}
function createMarker(place,icon) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: icon,
visible:true
});
markersArray.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent("<b>Name:</b>"+place.name+"<br><b>Address:</b>"+place.vicinity+"<br><b>Reference:</b>"+place.reference+"<br><b>Rating:</b>"+place.rating+"<br><b>Id:</b>"+place.id);
infowindow.open(map, this);
});
}
var source="";
var dest='';
function search_types(latLng){
clearOverlays();
if(!latLng){
var latLng = pyrmont;
}
var placename = $('.nearby h3').attr("data-value")
var type = $('#valueStored').val();
var icon = "images/"+type+".png";
var request = {
location: latLng,
radius: 2000,
types: [type], //e.g. school, restaurant,bank,bar,city_hall,gym,night_club,park,zoo
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
$('.map-list').find('li').remove();
var service = new google.maps.places.PlacesService(map);
service.search(request, function(results, status) {
map.setZoom(14);
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
results[i].html_attributions='';
places[i] = results[i];
createMarker(results[i],icon);
$('.map-list').append('<li>'+results[i].name+'<div><span class="distance"></span> <span class="duration"></span></div></li>');
}
}
});
distanceCalc();
}
var latadd, longadd;
function distanceCalc(latLng){
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
var changeaddress;
var pyrmont1 = new google.maps.LatLng(20.268455824834792, 85.84099235520011);
var request = {
origin: pyrmont,
destination: pyrmont1,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var listed = $('.map-list li');
console.log(places[4]);
for (var i = 0; i < listed.length; i++) {
$('.distance').text(response.routes[0].legs[0].distance.value);
$('.duration').text(response.routes[0].legs[0].duration.value);
}
// Display the distance:
directionsDisplay.setDirections(response);
}
});
}
function showResult(result) {
latadd = result.geometry.location.lat();
longadd = result.geometry.location.lng();
}
// Deletes all markers in the array by removing references to them
function clearOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setVisible(false)
}
//markersArray.length = 0;
}
}
google.maps.event.addDomListener(window, 'load', initialize);
function clearMarkers(){
$('#show_btn').show();
$('#hide_btn').hide();
clearOverlays()
}
function showMarkers(){
$('#show_btn').hide();
$('#hide_btn').show();
if (markersArray) {
for (i in markersArray) {
markersArray[i].setVisible(true)
}
}
}
I am using google map to find route between two location.i want to get center latitude and longitude of the route. can u please tell me how to get center of the route.i am using the below code for getting routes,Thanks in advance
var map;
var directionsDisplay;
var directionsService;
var stepDisplay;
var markerArray = [];
var infoWindow;
var service;
var lat1 = 0;
var lng1;
function pre_initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Current Location.'
});
map.setCenter(pos);
}, function () {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
function initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var addressfrom = document.getElementById("from").value;
var addressto = document.getElementById("to").value;
var geocoder = new google.maps.Geocoder();
var coords = new google.maps.LatLng(0, 0);
alert(lat1);
coords = geocoder.geocode({ 'address': addressfrom }, function (results, status) {
results[0].geometry.location.lat();
results[0].geometry.location.lng();
});
directionsService = new google.maps.DirectionsService();
// Create a renderer for directions and bind it to the map.
var rendererOptions = {
map: map
}
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions)
// Instantiate an info window to hold step text.
infoWindow = new google.maps.InfoWindow();
stepDisplay = new google.maps.InfoWindow();
calcRoute();
google.maps.event.addListenerOnce(map, 'bounds_changed', performSearch);
}
function performSearch() {
var request = {
bounds: map.getBounds(),
radius: 100,
types: ['hospital', 'cafe', 'restaurant', 'food', 'bar'],
keyword: 'best view'
};
service = new google.maps.places.PlacesService(map);
//service.nearbySearch(request, callback);
service.radarSearch(request, callback);
//service.textSearch(request, callback);
}
function callback(results, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
for (var i = 0, result; result = results[i]; i++) {
createMarker(result);
}
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon:
{
// Star
path: 'M 0,-24 6,-7 24,-7 10,4 15,21 0,11 -15,21 -10,4 -24,-7 -6,-7 z',
fillColor: '#ff0000',
fillOpacity: 1,
scale: 1 / 4,
strokeColor: '#bd8d2c',
strokeWeight: 1
}
});
google.maps.event.addListener(marker, 'click', function () {
service.getDetails(place, function (result, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
infoWindow.setContent(result.name);
infoWindow.open(map, marker);
});
});
}
function calcRoute() {
// First, remove any existing markers from the map.
for (var i = 0; i < markerArray.length; i++) {
markerArray[i].setMap(null);
}
// Now, clear the array itself.
markerArray = [];
var start = document.getElementById('from').value;
var end = document.getElementById('to').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var warnings = document.getElementById('warnings_panel');
warnings.innerHTML = '<b>' + response.routes[0].warnings + '</b>';
directionsDisplay.setDirections(response);
showSteps(response);
}
});
}
function showSteps(directionResult) {
var myRoute = directionResult.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
var marker = new google.maps.Marker({
position: myRoute.steps[i].start_point,
map: map
});
attachInstructionText(marker, myRoute.steps[i].instructions);
markerArray[i] = marker;
}
}
function attachInstructionText(marker, text) {
google.maps.event.addListener(marker, 'click', function () {
stepDisplay.setContent(text);
stepDisplay.open(map, marker);
});
}
</script>
Refer to the code below:
self.adjustPosition = function () {
var lat = 0, lng = 0;
if (self.nearbyPlaces().length == 0) {
return false;
}
for (var i = 0; i < self.nearbyPlaces().length; i++) {
lat += self.nearbyPlaces()[i].latitude;
lng += self.nearbyPlaces()[i].longitude;
}
lat = lat / self.nearbyPlaces().length;
lng = lng / self.nearbyPlaces().length;
self.map.setCenter(new window.google.maps.LatLng(lat, lng));
};
I might not be understanding how this works, but if I enter in #Model.name which would find an address (just make one up for your testing purposes) the following javascript should find me, find the destination and find me directions.
But it doesn't. Why doesn't it? There are no console errors.
function success(position) {
var s = document.querySelector('#status');
if (s.className == 'success') {
// not sure why we're hitting this twice in FF, I think it's to do with a cached result coming back
return;
}
s.innerHTML = "found you!";
s.className = 'success';
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcanvas';
mapcanvas.style.height = '400px';
mapcanvas.style.width = '560px';
document.querySelector('article').appendChild(mapcanvas);
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 15,
center: latlng,
mapTypeControl: false,
navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL },
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "You are here! (at least within a " + position.coords.accuracy + " meter radius)"
});
var request = {
origin: latlng,
destination: '#Model.id',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function error(msg) {
var s = document.querySelector('#status');
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
// console.log(arguments);
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
error('not supported');
}
you must define the map-option for directionsDisplay