I want to add functionality like gmap navigation into ionic hybrid application like blue dot pointer also. Previously I used geolocation API but Location is not changed when I change my position (I seem static). I want to add the live location tracking like google map. Can anyone suggest me the right way?
Use watchPosition and change marker on map. Something like:
var myMarker = null;
// get current position
navigator.geolocation.getCurrentPosition(showPosition);
// show current position on map
function showPosition(position) {
myMarker = new google.maps.Marker({
position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
map: new google.maps.Map(document.getElementById("map")),
icon: 'img/icons/myicon.png'
});
}
// watch user's position
navigator.geolocation.watchPosition(watchSuccess, watchError, watchOptions);
// change marker location everytime position is updated
function watchSuccess(position) {
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// set marker position
marker.setPosition(latLng);
}
You can also use $cordovaGeolocation plugin. Take a look at plugin docs.
getCurrentPosition returns current position of Geolocation
watchPosition returns current position every time it changes. So, with this function, you can change the marker on map everytime with setPosition and pass coordinates to it.
You can just apply to your map property the native method setMyLocationEnabled(true).
See my example:
let element: HTMLElement = document.getElementById('map');
this.map = this.googleMaps.create(element);
this.map.setMyLocationEnabled(true);
This last line will active a native current position marker.
in my case, it can not find watchSuccess, watchError, watchOptions here is my code
if (navigator.geolocation.watchPosition(watchSuccess, watchError, watchOptions)) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map.setCenter(pos);
that.MyLocation = new google.maps.LatLng(pos);
}, function() {
});
} else {
// Browser doesn't support Geolocation
}
directionsService.route({
origin: this.MyLocation,
destination: this.Destination,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
// watch user's position
// change marker location everytime position is updated
watchSuccess(position) {
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// set marker position
marker.setPosition(latLng);
}
Related
Using v.3 of the Google geocoder api with a Java back end, Velocity front end and an Oracle db.
Our current spec specifies that when a user selects a marker (lat/lng) that their zoom should be saved as well for future sessions. I can't for the life of me figure out how to do this. I have seen some information about bounds which I think I may be able to use in a hackey way, but I don't want to define the bounds of the map, I just want to save the zoom (like the lat/lng) and be able to pass it to the back end.
map.js
var geocoder;
var map;
var siteLocation;
var marker;
function initMap() {
var lat = parseFloat($("#newLat").val());
var lng = parseFloat($("#newLng").val());
geocoder = new google.maps.Geocoder();
siteLocation = { lat: lat, lng: lng };
map = new google.maps.Map(document.getElementById('map'),
{
center: siteLocation,
zoom: 19,
}
);
//set crosshair
console.log('setting waypoint marker');
crosshair = new google.maps.Marker(
{
position: siteLocation,
map: map,
draggable: false,
shape: { coords: [0, 0, 0, 0], type: 'rect' },
icon: "https://www.daftlogic.com/images/cross-hairs.gif"
}
);
crosshair.bindTo('position', map, 'center');
geocodeLatLng();
}
//use new selection to
function geocodeLatLng() {
var lat = crosshair.getPosition().lat();
var lng = crosshair.getPosition().lng();
var newLocation = crosshair.getPosition();
geocoder.geocode({ location : crosshair.position}, function(results, status) {
if (status == 'OK') {
results[0].geometry.location.lat();
results[0].geometry.location.lng();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
//get new user selected map options, [drop marker] (optional)
$("#addGeolocation").on("click", function (evt) {
geocodeLatLng();
evt.preventDefault();
var newZoom = map.getZoom();
var newLat = crosshair.getPosition().lat();
var newLng = crosshair.getPosition().lng();
$("#newLat").val(newLat);
$("#newLng").val(newLng);
newLocation = new google.maps.LatLng(newLat, newLng);
map.setCenter(newLocation);
map.setZoom(newZoom);
//make sure no marker exists
if ( marker !== undefined) {
marker.setPosition(newLocation);
} else {
marker = new google.maps.Marker({
position: newLocation,
map: map,
draggable: true
});
}
});
Velocity Macro
#macro(map $ADDRESS)
<script defer
src="https://maps.googleapis.com/maps/api/js?key=${GOOGLE_API_KEY}&callback=initMap">
</script>
<div id="map"></div>
<span class="innerBlock smallBlock" id="map" ></span>
<button type="button" onclick="geocodeLatLng()" id="addGeolocation"> $BTN_ADD_GEOLOCATION</button>
#inp_hidden("newLat" "$context.getSite().getLatitude()")
#inp_hidden("newLng" "$context.getSite().getLongitude()")
#inp_hidden("newZoom")
#end
I am completely stumped. Any ideas? Most of the solutions I have seen involve cookies but we cannot use those. Any advice would be appreciated. Thanks!
I think I understand what you mean but correct me if I'm wrong.
You could save the zoom level in a variable.
var zoom = 16;
and then save this in the local storage
localStorage.setItem("zoomLevel", zoom);
then use getItem method to retrieve it
var savedZoom = localStorage.getItem("zoomLevel");
So if you were planning to have the zoom levels in a select box or something, you can save the users choice into the local storage and then retrieve it when they return by setting to zoom to 'savedZoom' for example.
I'm not completely sure if this is what you were after but hopefully it helps. I've tried not to go into too much detail just incase it isn't.
First of all, I just started with JavaScript, so I'm not really good at it. I am making an app, using the Google Maps Places API, in which you can push a button and get your location, push another button and get nearby places (for example stores or bars) based on your location. Getting the location of the device works, but my code doesn't display the nearby places. It does go to the location, but it doesn't show the markers of the nearby places. I don't know what is going wrong, but I think it might have to do with the code for the markers or with the sequence of the code.
I am using Intel XDK (HTML5 + Cordova and the App Designer) and the Google Maps Places API. Right now it all happens when one button (with id="myloc-btn") is pushed, but (if both the location and the nearby places work) I want to seperate them in two buttons, one to show the location and one to show the nearby places.
Below is my javascript code. I have commented out the marker for the location of the device I originally had, because I thought it might be in the way of the markers for the nearby places.
Anyone know what's wrong or can help me?
Thanks in advance!
---UPDATE---
I tried the search nearby places from the Google Maps documentation (https://developers.google.com/maps/documentation/javascript/examples/place-search), with a set location (I basically copied and pasted the code), but that doesn't work either. Again it goes to the right location, but it doesn't display any markers. I tried it both in the simulator and on my phone, but it both has the same result. I don't know why the markers don't show
var map;
var service;
var infoWindow;
var pos;
var marker = [];
//var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
//var labelIndex = 0;
function register_event_handlers() {
$(document).on("click", "#myloc-btn", function(evt) {
initMap();
});
function initMap() {
map = new google.maps.Map(document.getElementById('gmap'), {zoom: 14});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
//addMarker(pos, map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
var request = {
location: pos,
radius: 5000,
type: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
/*
function addMarker(location, map) {
var marker = new google.maps.Marker({
map: map,
// Define the place with a location, a query string and a label.
place: {
location: location,
query: 'This is my location'
},
label: labels[labelIndex++ % labels.length],
});
// Construct a new InfoWindow.
var infoWindow = new google.maps.InfoWindow({
content: 'Here I am!'
});
// Opens the InfoWindow when marker is clicked.
marker.addListener('click', function() {
infoWindow.open(map, marker);
});
}
*/
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
document.addEventListener("app.Ready", register_event_handlers, false);
})();
In the callback provided to getCurrentPosition(), you're setting pos. However, this callback will get called after the phone has determined the location, i.e. at some random point in the future. Which is long after you're trying to use that pos in your request for the places. You need to move the places code in its own function, then call it while passing the map and pos, after you have centered the map. Almost exactly what you already did with addMarker().
I am trying to show the distance between two points. but i am facing this error direction request failed due to not found. I googled but not found a solution. Please have a look at my code and tell me if i am doing something wrong.
function initAutocomplete() {
var markerArray = [];
// Instantiate a directions service.
var directionsService = new google.maps.DirectionsService;
// Create a map and center it on Manhattan.
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 13,
center: {lat: 40.771, lng: -73.974}
});
// Create a renderer for directions and bind it to the map.
var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
// Instantiate an info window to hold step text.
var stepDisplay = new google.maps.InfoWindow;
// Display the route between the initial start and end selections.
calculateAndDisplayRoute(
directionsDisplay, directionsService, markerArray, stepDisplay, map);
// Listen to change events from the start and end lists.
var onChangeHandler = function() {
calculateAndDisplayRoute(
directionsDisplay, directionsService, markerArray, stepDisplay, map);
};
document.getElementById('start').addEventListener('change', onChangeHandler);
document.getElementById('end').addEventListener('change', onChangeHandler);
}
function calculateAndDisplayRoute(directionsDisplay, directionsService,
markerArray, stepDisplay, map) {
// First, remove any existing markers from the map.
for (var i = 0; i < markerArray.length; i++) {
markerArray[i].setMap(null);
}
// Retrieve the start and end locations and create a DirectionsRequest using
// WALKING directions.
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
travelMode: google.maps.TravelMode.WALKING
}, function(response, status) {
// Route the directions and pass the response to a function to create
// markers for each step.
if (status === google.maps.DirectionsStatus.OK) {
document.getElementById('warnings-panel').innerHTML =
'<b>' + response.routes[0].warnings + '</b>';
directionsDisplay.setDirections(response);
showSteps(response, markerArray, stepDisplay, map);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
function showSteps(directionResult, markerArray, stepDisplay, map) {
// For each step, place a marker, and add the text to the marker's infowindow.
// Also attach the marker to an array so we can keep track of it and remove it
// when calculating new routes.
var myRoute = directionResult.routes[0].legs[0];
for (var i = 0; i < myRoute.steps.length; i++) {
var marker = markerArray[i] = markerArray[i] || new google.maps.Marker;
marker.setMap(map);
marker.setPosition(myRoute.steps[i].start_location);
attachInstructionText(
stepDisplay, marker, myRoute.steps[i].instructions, map);
}
}
function attachInstructionText(stepDisplay, marker, text, map) {
google.maps.event.addListener(marker, 'click', function() {
// Open an info window when the marker is clicked on, containing the text
// of the step.
stepDisplay.setContent(text);
stepDisplay.open(map, marker);
});
}
Html side :
<input id="start" class="controls" type="text"
placeholder="picup lock">
<input id="end" class="controls" type="text"
placeholder="drop off">
Based from this documentation, error NOT_FOUND indicates at least one of the locations specified in the request's origin, destination, or waypoints could not be geocoded.
Make sure that point1 and point3 are not empty. The API doesn't know how to create a route from "" to "".
Check this related ticket and tutorial.
I had the same issue yesterday, using the API via C# httpClient. But the same request worked fine in a browser. After a bit of debugging I found out that it only worked if I sent Accept-Language header in the httpClient…
I am working on a website that have multiple companies and employees, each company should register by entering its username,password and location on Google maps.
The location is going to appear to employees who are using an android application (Which is connected to the same website's database).
I want to know how to allow the company to specify their exact address either by typing the decimal points of the location or by using the pin to specify it on Google map or by allowing me to detect their location.
I read this: https://developers.google.com/maps/documentation/javascript/tutorial
but I do not know if it is what I need in my case.
Note that it is the first time for me to deal with maps so I am not deep into it.
I hope i understand you correctly.
One option could be something like this:
Get the user device' geolocation and put that position on a map with a draggable marker.
If the position is not correct, marker can be dragged and you will get the new coords - if the marker location has been changed.
Here is the code (with jquery):
var map;
var marker;
function initialize() {
var mapOptions = {
zoom: 11
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var marker = new google.maps.Marker({
position: pos,
map: map,
title: 'Here you are',
draggable: true
});
$('#user-info').append('Location found using HTML5<br/>');
map.setCenter(pos);
google.maps.event.addListener(marker, 'dragend', function(a) {
$('#user-info').append(a.latLng.lat().toFixed(4) + ', ' + a.latLng.lng().toFixed(4) +'<br/>' );
});
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
$('#user-info').append('Error: The Geolocation service failed.');
} else {
$('#user-info').append('Error: Your browser doesn\'t support geolocation.');
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
};
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
http://jsfiddle.net/iambnz/xdoc1nxm/
I hope this will help you.
In case you will need to get the exact address, you have to add geocoding functionality.
I'm building a mobile map using the Google Map API V3. The is a little different than a standard map in that I have categories of markers than you can turn on/off. Everything works great, but I can't seem to get geolocation working. I've tried every combination and code snippet I can find and at most I can get it to register the location request, but it will not display a marker there no matter what I do. I'm sure I'm doing something very simple wrong, but I'm very new to Javascript so the answer is evading me.
Here is a shortened version of my current code (contains an example of everything, but cuts out a lot of the repetitive variables). This example doesn't include the geolocation functions since I've tried so many in different ways I'm not sure which one I would even put on here. The toggleMarkers() function is what I'm using to turn on/off the markers and I'm guessing that's where the problem is for the geolocation marker being displayed. If you could show me how to implement geolocation within this code I would greatly appreciate it!
var markers = [];
function initialize() {
//Setting Map
var mapOptions = {
zoom: 18,
center: new google.maps.LatLng(45.73158,-122.636277),
mapTypeId: 'satellite'
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(0);
//Marker Categories
var markerBuildings = {
category: 'buildings',
}
var markerParking = {
category: 'parking',
}
// Icons
var iconBuilding = new google.maps.MarkerImage('images/building.png',
new google.maps.Size(32, 37),
new google.maps.Point(0,0),
new google.maps.Point(16,32));
var iconAmphitheater = new google.maps.MarkerImage('images/amphitheater.png',
new google.maps.Size(32, 37),
new google.maps.Point(0,0),
new google.maps.Point(16,32));
//Coordinates
//Buildings
var vmcb = new google.maps.Marker({
position: new google.maps.LatLng(45.730513,-122.638106),
map: map,
url: 'http://www.google.com/',
icon: iconBuilding,
data: markerBuildings
});
markers.push(vmcb);
var vadm = new google.maps.Marker({
position: new google.maps.LatLng(45.730899,-122.637742),
map: map,
url: 'http://www.google.com/',
icon: iconBuilding,
data: markerBuildings
});
markers.push(vadm);
}
function toggleMarkers(attr,val) {
if (markers){
for (i in markers) {
if(markers[i].data[attr] == val){
var visibility = (markers[i].getVisible() == true) ? false : true;
markers[i].setVisible(visibility);
}
}
}
}
If you could show me how to implement geolocation within this code I would greatly appreciate it!
call getGeoLocation() (below) after you create the map object
function getGeoLocation() {
// http://stackoverflow.com/questions/3397585/navigator-geolocation-getcurrentposition-sometimes-works-sometimes-doesnt
var options = null;
if (navigator.geolocation) {
if (!browserChrome) {
// By using the 'maximumAge' option, the position
// object is guaranteed to be at most 15 seconds old.
// FF and Safari seem to like these options; Chrome does not
options={enableHighAccuracy: false, maximumAge: 15000, timeout: 30000};
}
else {
// Request a position. We only accept cached positions, no matter what
// their age is. If the user agent does not have a cached position at
// all, it will immediately invoke the error callback.
// http://dev.w3.org/geo/api/spec-source.html
// Chrome will not allow this submitted via the file:// protocol
options={maximumAge:Infinity, timeout:0};
}
navigator.geolocation.getCurrentPosition(function(position) {
centerIsSet = true
canGeolocate = true;
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(pos);
},
getGeoLocationErrorCallback(true),
options);
}
else {
// browser doesn't support geolocation
getGeoLocationErrorCallback(false);
}
}