I want let user mark their position in our google maps application and then save it to our database, then it can be showed in our google maps application in the next time.
If you want to save the position where the user clicked you can use a "click" listener to get the latitude and longitude of the click with code like this then send it to your server using an Ajax style call where it can be stored in the database.
var clickListener = GEvent.addListener(map,"click",
function (overlay,latlng,overlaylatlng) {
alert(latlng);
});
This code is for v2 of the Google Maps API. Version 3 should have something similar.
An options is to try geolocation first and let the browser pinpoint them. If the browser doesn't support geolocation or an error occurs you can fall back onto them manually adding their position.
var geolocation = null; // holds the latlng object
navigator.geolocation.getCurrentPosition( geolocation_success_init, geolocation_error_init, {enableHighAccuracy: false, timeout: 10000} );
function geolocation_success_init( position ) {
geolocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
initialize_map();
}
function geolocation_error_init( error ){
initialize_map();
}
when you create your map check for geolocation
if ( geolocation ) {
marker = new google.maps.Marker({
position: geolocation,
map:.map,
title: "Your Location"
});
}
Related
I'm trying to update the current location on map view. I get the current location in controller:
var updateCurrentLocation = function updateCurrentLocation(e){
Ti.API.info("Update current location on map");
$.map.setLocation({
latitude: e.coords.latitude,
longitude: e.coords.longitude,
latitudeDelta: 1,
longitudeDelta: 1
});
}
But the problem is that at this time the code run, the map view has not been created yet, so it cannot update the current location.
Can any one suggest some technique to solve this problem?
Thank you!
Are you not creating the map in the same controller? If you are just place the code after the map code, but that is obvious so I will assume you have thought of that.
Why not set the coords to the current user coords when you create the Map?
Worst case scenario, you can use setTimer(, timer ms) to call a function after a set amount of time if you wanted to call the updateCurrentLocation function after 500 milliseconds. This is not ideal.
starting up the map controller
function showMap() {
// create the new controller and pass in the
// model object as an argument 'item'
var ctrl = Alloy.createController('MapView', {
'item' : args.item // <-- pass is information + coords for map
});
setTimeout(function() {
args.photoListTab.open(ctrl.mainWindow);
}, 200);
}
in map controller
// get the photo object from the parameters
var coords = args.item.custom_fields.coordinates[0];
var locationString = args.item.custom_fields.location_address;
// create annotation
var annotation = Alloy.Globals.Map.createAnnotation({
latitude : Number(coords[1]),
longitude : Number(coords[0]),
title : args.item.custom_fields.location_string,
myid : args.item.id
});
complete solution here https://github.com/aaronksaunders/testInClass
Eventually I found there is a event call "complete" on the Map View. So, to do anything that you want to happen after the map loaded, in Map controller, use:
$.map.addEventListener('complete', function(e) {
Ti.API.info("Map controller: on Map complete");
$.trigger('complete', e); // Trigger event for other controller can listen too.
// And you can do other logic here.
});
Reference from Titanium Doc
I am doing a vehicle traking project, i am getting coordiantes from the databases, and showing on the google maps.
here is my code.....!!
function get_coordinates(checkbox){
var v_id=checkbox.id;
if(checkbox.checked){
var hr = new XMLHttpRequest();
hr.open("POST", "fetch_coordinates.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
var lat=data.loc.lat;
var lon=data.loc.lon;
addmarker(lat,lon,v_id);
}
}
hr.send("id="+v_id);
} else{
var mark = markers[v_id]; // find the marker by given id
mark.setMap(null);
delete markers[v_id];
}
}
function addmarker(lat,lon,v_id){
var marker = new google.maps.Marker({
id: v_id,
position: new google.maps.LatLng(lat, lon),
zoom: 8,
map: map,
title: 'Vehicle No: '+v_id,
icon: 'live.gif',
optimized:false
});
markers[v_id] = marker;
bounds.extend(new google.maps.LatLng(lat,lon));
// map.setOptions({center:new google.maps.LatLng(lat,lon),zoom:8});
map.fitBounds(bounds);
}
But the problem is, sometimes i get GPS coordiantes which are 1,2 inches away from the road (possibly because of less precison of device or signal distortion etc)
How should I force my marker to automatically adjust on the road? Is there a some way, using direction rendering or any other hint ??? please help
In 2017 the right way to do it is the Roads API Snap to Roads service.
You can read about this web service on
https://developers.google.com/maps/documentation/roads/snap
The Google Maps Roads API takes up to 100 GPS points collected along a route, and returns a similar set of data, with the points snapped to the most likely roads the vehicle was traveling along. Optionally, you can request that the points be interpolated, resulting in a path that smoothly follows the geometry of the road.
https://developers.google.com/maps/documentation/directions/intro
You can use your desired url to get json request..
In the Coding section you can write this code to get the location on the road..
Marker liveloc;
JSONObject obj1=new JSONObject(s);
JSONArray arr1=obj1.getJSONArray("routes");
for (int i=0;i<arr1.length();i++){
JSONObject obj2=arr1.getJSONObject(i);
JSONArray arr2=obj2.getJSONArray("legs");
JSONObject obj3=arr2.getJSONObject(0);
JSONObject obj4=obj3.getJSONObject("start_location");
String k=obj4.getString("lat");
String k2=obj4.getString("lng");
double k3=Double.parseDouble(k);
double k4=Double.parseDouble(k2);
LatLng myloc=new LatLng(k3,k4);
if (liveloc !=null){
liveloc.remove();
}
liveloc=mMap.addMarker(new MarkerOptions().position(myloc));
}
You need to get the first start location from the json request..
Hope it helps...
I have a google map and I am wanting to show this KML file, I can load the KML but I haven't yet figured out how to clear it off the map. I load the KML on the map when the user click a check box, but whe they uncheck the box the KML wont go away. Here is the code that I am using to load the KML.
var isShowData = false;
//showEMSz(null);
var tileEMSz;
function showEMSz(obj) {
isShowData = !isShowData;
if (isShowData) {
tileEMSz = new google.maps.KmlLayer({
url: '/ELTSCAD.kml'
});
tileEMSz.setMap(map);
}
else
{
// remove Option
tileEMSz = null;
}
}
set the map-property of the layer to null:
if(tileEMSz){tileEMSz.setMap(null);}
I am building an app using javascript, google maps v2 and ESRI 10.1.
I have a DynamicMapServiceLayer and a single layer in my ESRI map service. I dynamically show or hide features on the layer using the ESRI setLayerDefinitions function based on filter values selected by the user at runtime.
When the user clicks on the map I use the ESRI IdentifyTask object to find what the user clicked on. I want to show an infowindow for the feature the user clicked on. My code is sort of working but it opens infowindows for features that are filtered out (not visible) on the layer.
How can I check to see if the user clicked on a visible feature and stop opening infowindows for hidden features? Or how can I get IdentifyTask to stop including hidden features in the response object it returns?
This is my identifyParameters task invoke set up
// set the identify parameters
var identifyParameters = new esri.arcgis.gmaps.IdentifyParameters();
identifyParameters.geometry = latLng; // where the user clicked on the map
identifyParameters.tolerance = 3;
identifyParameters.layerIds = [OUTAGES_LAYER];
identifyParameters.layerOption = 'all';
identifyParameters.bounds = map.getBounds();
var mapSize = map.getSize();
identifyParameters.width = mapSize.width;
identifyParameters.height = mapSize.height;
// execute the identify operation
identifyTask.execute(identifyParameters, function(response, error) {
if (hasErrorOccurred(error)) return;
addResultToMap(response, latLng);
});
UPDATE
I have upgraded to Google maps v3. Now the identify parameters support passing layerdef information as follows below. For example I can limit the identify operation to those features where FISCAL_YEAR = 2014. My problem is solved.
function identify(evt) {
dynamicMap.getMapService().identify({
'geometry': evt.latLng,
'tolerance': 3,
'layerIds': [12],
'layerOption': 'all',
'layerDefs': {12 : 'FISCAL_YEAR = 2014'},
'bounds': map.getBounds(),
'width': map.getDiv().offsetWidth,
'height': map.getDiv().offsetHeight
}, function(results, err) {
if (err) {
alert(err.message + err.details.join('\n'));
} else {
addResultToMap(results, evt.latLng);
}
});
}
I just started working using Google Maps API yesterday, and trying to set up drive directions to my map. My problem is: when I call the function load,
// [...]
gdir = new GDirections(map, directionsPanel);
// [...]
gdir.load("from: " + fromAddress + " to: " + toAddress);
it returns a map whose markers are not draggable. So, I need to make them draggable in order to recalculate the directions, but I can't get the markers objects.
Someone knows how can I do it?
You need to add a handler on the GDirections object for the addoverlay event:
GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay);
When your onGDirectionsAddOverlay handler is called you can iterate through the new markers and replace them with draggable copies:
for (var i = 0; i <= gdir.getNumRoutes(); i++)
{
var originalMarker = gdir.getMarker(i);
latLngs[i] = originalMarker.getLatLng();
icons[i] = originalMarker.getIcon();
newMarkers[i] = new GMarker(latLngs[i], { icon: icons[i], draggable: true, title: 'Kan flyttes' });
map.addOverlay(newMarkers[i]);
// add stuff to your newMarkers[i] drag end event...
// ...
//Bind 'click' event to original markers 'click' event
copyClick(newMarkers[i], originalMarker);
// Now we can remove the original marker safely
map.removeOverlay(originalMarker);
}
You can find a working example of this here (source).