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.
Related
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>
I am working on core PHP, i wants to fecth location based record.
i want exact search for google map,like if i search (implemented autocomplete search) for (BTM layout) means BTM layout google map should come how will do this please help any one.
Here is my HTML form:
<form action="pglist.php" id="location_search" class="form-inline" method="POST" >
<div class="form-group keyword">
<input id="locationTextField" name= "list" type="text" size="50">
<button type="submit" name="filter"><img src="assets/images/search.png" alt="Rentozy" /></button>
</div>
</form>
Here is my database query:
$locations=array();
$query = $conn->query('SELECT `pg_address` FROM `tbl_master_property`');
while ($row = $query->fetch_assoc()) {
$locations[] = $row['pg_address'];
}
$locations = json_encode($locations);
Here my google map script code:
<div class="map">
<div id="map"></div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyBAM5Cs2VsrOBs8Idqy0t0o6vw4hEU0Lys">
</script>
<script type="text/javascript">
var delay = 100;
var infowindow = new google.maps.InfoWindow();
var latlng = new google.maps.LatLng(12.9716, 77.5946);
var mapOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var bounds = new google.maps.LatLngBounds();
function geocodeAddress(address, next) {
geocoder.geocode({address:address}, function (results,status)
{
if (status == google.maps.GeocoderStatus.OK) {
var p = results[0].geometry.location;
var lat=p.lat();
var lng=p.lng();
createMarker(address,lat,lng);
}
else {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
nextAddress--;
delay++;
} else {
}
}
next();
}
);
}
function createMarker(add,lat,lng) {
var contentString = add;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
animation: google.maps.Animation.DROP,
draggable: true,
map: map,
});
marker.addListener('click', toggleBounce);
function toggleBounce() {
if (marker.getAnimation() !== null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
bounds.extend(marker.position);
}
var locations = <?= $locations ?>;
console.log(locations);
var nextAddress = 0;
function theNext() {
if (nextAddress < locations.length) {
setTimeout('geocodeAddress("'+locations[nextAddress]+'",theNext)', delay);
nextAddress++;
} else {
map.fitBounds(bounds);
}
}
theNext();
</script>
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': 'BTM layout'}, function(results, status) {
if (status === 'OK') {
Map.setCenter(results[0].geometry.location);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
You could request the location using geocoder and handle exceptions.
I want to add this forecast to the infowindow. I wanna use Google weather layers. But i dont know how to put them to the current infowindow
var weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.FAHRENHEIT
});
var cloudLayer = new google.maps.weather.CloudLayer();
How can i add forecast to the current info window, after details of location?
Thank you
function showPosition(position) {
var googlePos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
zoom: 12,
center: googlePos,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var mapObj = document.getElementById('divmap');
var googleMap = new google.maps.Map(mapObj, mapOptions);
var markerOpt = {
map: googleMap,
position: googlePos,
title: 'Hi , I am here',
animation: google.maps.Animation.DROP
};
var googleMarker = new google.maps.Marker(markerOpt);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': googlePos
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var popOpts = {
content: results[1].formatted_address,
position: googlePos
};
var popup = new google.maps.InfoWindow(popOpts);
/*google.maps.event.addListener(googleMap, 'center_changed', function(){
window.setTimeout(function(){
googleMap.panTo(googleMarker.getPosition());
}, 2000);
});*/
google.maps.event.addListener(googleMarker, 'setTimeout', setTimeout(function () {
popup.open(googleMap, googleMarker)
}, 200));
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
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));
};
Im trying to change geocoded informations from Schwartmecke 49, 57399 Kirchhundem, Germany to just Schwartmecke 49, Germany , but dont know how. Can anybode help me ? Thanks
<script type="text/javascript">
var map;
var geocoder;
var centerChangedLast;
var reverseGeocodedLast;
var currentReverseGeocodeResponse;
function initialize() {
var latlng = new google.maps.LatLng(49.624935522974546, 15.46877500000007);
var myOptions = {
zoom: 7,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder = new google.maps.Geocoder();
setupEvents();
centerChanged();
}
function setupEvents() {
reverseGeocodedLast = new Date();
centerChangedLast = new Date();
setInterval(function() {
if((new Date()).getSeconds() - centerChangedLast.getSeconds() > 1) {
if(reverseGeocodedLast.getTime() < centerChangedLast.getTime())
reverseGeocode();
}
}, 1000);
google.maps.event.addListener(map, 'zoom_changed', function() {
document.getElementById("zoom_level").innerHTML = map.getZoom();
});
google.maps.event.addListener(map, 'center_changed', centerChanged);
google.maps.event.addDomListener(document.getElementById('crosshair'),'dblclick', function() {
map.setZoom(map.getZoom() + 1);
});
}
function getCenterLatText() {
return '(' + map.getCenter().lat() +')';
}
function getCenterLngText() {
return '(' + map.getCenter().lng() +')';
}
function centerChanged() {
centerChangedLast = new Date();
var lat = getCenterLatText();
var lng = getCenterLngText();
document.getElementById('lat').innerHTML = lat;
document.getElementById('lng').innerHTML = lng;
document.getElementById('formatedAddress').value = '';
currentReverseGeocodeResponse = null;
}
function reverseGeocode() {
reverseGeocodedLast = new Date();
geocoder.geocode({latLng:map.getCenter()},reverseGeocodeResult);
}
function reverseGeocodeResult(results, status) {
currentReverseGeocodeResponse = results;
if(status == 'OK') {
if(results.length == 0) {
document.getElementById('formatedAddress').value = 'None';
} else {
document.getElementById('formatedAddress').value = results[0].formatted_address;
}
} else {
document.getElementById('formatedAddress').value = 'Error';
}
}
function geocode() {
var address = document.getElementById("address").value;
geocoder.geocode({
'address': address,
'partialmatch': true}, geocodeResult);
}
function geocodeResult(results, status) {
if (status == 'OK' && results.length > 0) {
map.fitBounds(results[0].geometry.viewport);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
}
function addMarkerAtCenter() {
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map
});
if(currentReverseGeocodeResponse) {
var addr = '';
if(currentReverseGeocodeResponse.size == 0) {
addr = 'None';
} else {
addr = currentReverseGeocodeResponse[0].formatted_address;
}
text = '<br>' + 'address: <br>' + addr;
}
var infowindow = new google.maps.InfoWindow({ content: text });
}
</script>
Hope i explained my problem enough.
In your reverseGeocodeResult() function, you take the first result and return its "formatted address" property.
Instead of returning this, try browsing its "address_components" property.
See more at
https://developers.google.com/maps/documentation/geocoding/#JSON