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>
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
Firstly, I have been checking all over the web but I couldnt find an answer.
I combined autocomplete with goole maps and if a user wants, he/she can move the marker as well and I get address from it. You can find the code below.
When a user searches for instance Nice, France, is it possible to fit Nice from e.g borders to my map? Maybe I have to change the zoom dynamically or I need to set new viewport, I am not sure. So far what I found is, I can give a distance and create a circle to fit that circle to the viewport. But circle's radius is set, so it can fit to Nice but can not fit to Miami.
Hope I could explain what I mean. Thank you in advance.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
#map_canvas {
width: 980px;
height: 500px;
}
#current {
padding-top: 5px;
}
</style>
</head>
<body>
<label>Enter address:</label><br>
<input id="searchTextField" type="text" size="50" style="margin-bottom: 20px;">
<section>
<div id='map_canvas' style=""></div>
<div id="current">No info...</div>
</section>
<div style="margin-top: 10px;" id="data_area">
</div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: new google.maps.LatLng(41.0082, 28.9784),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(41.0082, 28.9784),
draggable: true
});
var geocoder = new google.maps.Geocoder;
var markers = [];
markers.push(myMarker);
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
map.addListener('idle', function() {
console.log(map.getBounds());
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
});
google.maps.event.addListener(autocomplete, 'place_changed', function () {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
var place = autocomplete.getPlace();
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(place.geometry.location.lat(), place.geometry.location.lng()),
draggable: true
});
markers.push(myMarker);
map.setCenter(myMarker.position);
myMarker.setMap(map);
google.maps.event.clearListeners(myMarker, 'dragend');
google.maps.event.clearListeners(myMarker, 'dragstart');
drag(myMarker, geocoder, map);
});
drag(myMarker, geocoder, map);
map.setCenter(myMarker.position);
myMarker.setMap(map);
}
function drag(myMarker, geocoder, map) {
geocodeLatLng(geocoder, map, myMarker.getPosition().lat(), myMarker.getPosition().lng());
google.maps.event.addListener(myMarker, 'dragend', function (evt) {
document.getElementById('current').innerHTML = '<p>Lat: ' + evt.latLng.lat().toFixed(3) + ' Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
geocodeLatLng(geocoder, map, evt.latLng.lat(), evt.latLng.lng());
});
google.maps.event.addListener(myMarker, 'dragstart', function (evt) {
document.getElementById('current').innerHTML = '<p>Waiting...</p>';
});
}
function geocodeLatLng(geocoder, map, lat, lng) {
var input = lat + "," + lng;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
console.log(results[0])
var data_arr = []
document.getElementById("data_area").innerHTML = "";
var data_country = results[0].address_components.find(function(element) {
return element.types[0] == "country";
});
var data_administrative_1 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_1";
});
var data_administrative_2 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_2";
});
var data_administrative_3 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_3";
});
var data_administrative_4 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_4";
});
var data_route = results[0].address_components.find(function(element) {
return element.types[0] == "route";
});
if (data_route !== undefined) {data_arr.push(data_route["long_name"]);}
if (data_administrative_4 !== undefined) {data_arr.push(data_administrative_4["long_name"]);}
if (data_administrative_3 !== undefined) {data_arr.push(data_administrative_3["long_name"]);}
if (data_administrative_2 !== undefined) {data_arr.push(data_administrative_2["long_name"]);}
if (data_administrative_1 !== undefined) {data_arr.push(data_administrative_1["long_name"]);}
if (data_country !== undefined) {data_arr.push(data_country["long_name"]);}
data_arr.forEach(function(data) {
var node = document.createElement("LI");
var textnode = document.createTextNode(data);
node.appendChild(textnode);
document.getElementById("data_area").appendChild(node);
});
} else {
window.alert('No data!');
}
} else {
window.alert('Geocoder failed: ' + status);
}
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?libraries=places&key=MY_API_KEY&callback=initMap"></script>
</body>
</html>
The Autocomplete service returns the geometry of the location selected, zoom the map to show those bounds (in the fiddle/snippet I added a rectangle to show the bounds returned, if you don't want that displayed, remove it):
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else if (place.geometry.bounds) {
map.fitBounds(place.geometry.bounds);
}
proof of concept fiddle
html,
body {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
}
#map_canvas {
width: 100%;
height: 80%;
}
#current {
padding-top: 5px;
}
<label>Enter address:</label><br>
<input id="searchTextField" type="text" size="50" style="margin-bottom: 20px;">
<section style="width: 100%; height:100%;">
<div id='map_canvas' style=""></div>
<div id="current">No info...</div>
</section>
<div style="margin-top: 10px;" id="data_area"></div>
<script>
var rect;
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: new google.maps.LatLng(41.0082, 28.9784),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(41.0082, 28.9784),
draggable: true
});
var geocoder = new google.maps.Geocoder;
var markers = [];
markers.push(myMarker);
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
map.addListener('idle', function() {
console.log(map.getBounds());
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
if (rect && rect.setMap) rect.setMap(null);
rect = new google.maps.Rectangle({
map: map,
bounds: place.geometry.viewport
})
} else if (place.geometry.bounds) {
map.fitBounds(place.geometry.bounds);
if (rect && rect.setMap) rect.setMap(null);
rect = new google.maps.Rectangle({
map: map,
bounds: place.geometry.bounds
})
}
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(place.geometry.location.lat(), place.geometry.location.lng()),
draggable: true
});
markers.push(myMarker);
map.setCenter(myMarker.position);
myMarker.setMap(map);
google.maps.event.clearListeners(myMarker, 'dragend');
google.maps.event.clearListeners(myMarker, 'dragstart');
drag(myMarker, geocoder, map);
});
drag(myMarker, geocoder, map);
map.setCenter(myMarker.position);
myMarker.setMap(map);
}
function drag(myMarker, geocoder, map) {
geocodeLatLng(geocoder, map, myMarker.getPosition().lat(), myMarker.getPosition().lng());
google.maps.event.addListener(myMarker, 'dragend', function(evt) {
document.getElementById('current').innerHTML = '<p>Lat: ' + evt.latLng.lat().toFixed(3) + ' Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
geocodeLatLng(geocoder, map, evt.latLng.lat(), evt.latLng.lng());
});
google.maps.event.addListener(myMarker, 'dragstart', function(evt) {
document.getElementById('current').innerHTML = '<p>Waiting...</p>';
});
}
function geocodeLatLng(geocoder, map, lat, lng) {
var input = lat + "," + lng;
var latlngStr = input.split(',', 2);
var latlng = {
lat: parseFloat(latlngStr[0]),
lng: parseFloat(latlngStr[1])
};
geocoder.geocode({
'location': latlng
}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
console.log(results[0])
var data_arr = []
document.getElementById("data_area").innerHTML = "";
var data_country = results[0].address_components.find(function(element) {
return element.types[0] == "country";
});
var data_administrative_1 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_1";
});
var data_administrative_2 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_2";
});
var data_administrative_3 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_3";
});
var data_administrative_4 = results[0].address_components.find(function(element) {
return element.types[0] == "administrative_area_level_4";
});
var data_route = results[0].address_components.find(function(element) {
return element.types[0] == "route";
});
if (data_route !== undefined) {
data_arr.push(data_route["long_name"]);
}
if (data_administrative_4 !== undefined) {
data_arr.push(data_administrative_4["long_name"]);
}
if (data_administrative_3 !== undefined) {
data_arr.push(data_administrative_3["long_name"]);
}
if (data_administrative_2 !== undefined) {
data_arr.push(data_administrative_2["long_name"]);
}
if (data_administrative_1 !== undefined) {
data_arr.push(data_administrative_1["long_name"]);
}
if (data_country !== undefined) {
data_arr.push(data_country["long_name"]);
}
data_arr.forEach(function(data) {
var node = document.createElement("LI");
var textnode = document.createTextNode(data);
node.appendChild(textnode);
document.getElementById("data_area").appendChild(node);
});
} else {
window.alert('No data!');
}
} else {
window.alert('Geocoder failed: ' + status);
}
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>
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);
});
};
}
}
I am new to ionic, i integrate map with source and destination fields.
I want to address text should be changed its value on marker dragend event.
i am using $apply() for it but its not working.
here is my controller script:
.controller('RequestForRideCtrl', function ($scope, $ionicHistory, $http, $ionicPopup, $state, $window, $compile,$timeout) {
var Slat, Slng, Dlat, Dlng;
var Slatlng, Destination;
$scope.location = {};
$scope.location1 = {};
$scope.init = function () {
var Smarker, Dmarker;
var flag;
var myLatlng = new google.maps.LatLng(19.9975, 73.7898);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
var contentString = "<div><a ng-click=''>Click</a></div>";
var compiled = $compile(contentString)($scope);
var infowindow = new google.maps.InfoWindow({
content: compiled[0]
});
navigator.geolocation.getCurrentPosition(function (pos) {
$scope.map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
Slat = pos.coords.latitude;
Slng = pos.coords.longitude;
var myLatlng = new google.maps.LatLng(Slat, Slng);
$scope.map.setCenter(myLatlng);
Smarker = new google.maps.Marker({
position: myLatlng,
map: $scope.map,
draggable: true,
title: 'Source',
label: 'S'
});
google.maps.event.addListener(Smarker, 'drag', function (event) {
var lat = document.getElementById("latbox").value = this.getPosition().lat();
var lng = document.getElementById("lngbox").value = this.getPosition().lng();
Slatlng = new google.maps.LatLng(lat, lng);
flag=1;
getPosition(Slatlng, flag);
})});
$scope.$on('destination', function (evt, value) {
$scope.variable = value;
var Dlat = $scope.variable.geometry.location.lat();
var Dlng = $scope.variable.geometry.location.lng();
var myLatlngD = new google.maps.LatLng(Dlat, Dlng);
$scope.map.setCenter(myLatlngD);
var Dmarker = new google.maps.Marker({
position: myLatlngD,
map: $scope.map,
draggable: true,
title: 'Destination',
label: 'D'
});
google.maps.event.addListener(Dmarker, 'drag', function (event) {
var lat = document.getElementById("latbox1").value = this.getPosition().lat();
var lng = document.getElementById("lngbox1").value = this.getPosition().lng();
Destination = new google.maps.LatLng(lat, lng);
flag = 0;
getPosition(Destination, flag);
});
function getPosition(marker, flag) {
if (flag == 1) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': marker}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
$scope.location.formatted_address = results[1].formatted_address;
$timeout(function () {
$scope.$apply(function () {
console.log('in source');
});
}, 2000);
} else {
console.log('Location not found');
}
} else {
console.log('Geocoder failed due to: ' + status);
}
});
}
else {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': marker}, function (results, status, element) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
$scope.location1.formatted_address = results[1].formatted_address;
$timeout(function () {
$scope.$apply(function () {
console.log('in des');
});
}, 2000);
} else {
console.log('Location not found');
}
} else {
console.log('Geocoder failed due to: ' + status);
}
});
}
}
this is my html:
<ion-pane>
<div id="map" data-tap-disabled="true">
</div>
<div id="floating-panel" style="">
<input type="text" id="source1" placeholder="Source" location-suggestion location="location" ng-model="location.formatted_address">
</div>
<div id="floating-panel1" style="">
<input type="text" id="address" placeholder="Destination" location-Destination location1="location1" ng-model="location1.formatted_address">
</div>
</ion-pane>
help me to sort out this issue.
Try using $timeout instead of setTimeout. setTimeout function does not trigger $digest cycle.
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));
};