im trying to set the center of my google maps to my 2 defined Markes with Google Map Api V3.
But it centers just the first marker, the locationmarker.
i have this code that renders a map:
openShops : function(data) {
if (Ext.ComponentManager.get('shops-details') == undefined) {
Ext.create('Oxfam.view.ShopsDetails');
}
var shopsDetailsPage = Ext.ComponentManager.get('shops-details');
Ext.Viewport.setActiveItem(shopsDetailsPage);
var bounds;
var map = Ext.create('Ext.Map', {
id : 'shopMap',
xtype : 'map',
useCurrentLocation : {
autoUpdate : false
},
listeners : {
maprender : function(comp, map) {
var image = 'img/oxfamLogoSmall.png';
var locationMarker = new google.maps.Marker({
position : new google.maps.LatLng(this._geo
.getLatitude(), this._geo.getLongitude()),
map : map
});
var shopCoord = new google.maps.LatLng(sessionStorage
.getItem('longitude'), sessionStorage
.getItem('latitude'));
var locCoord = new google.maps.LatLng(this._geo
.getLatitude(), this._geo.getLongitude());
bounds = new google.maps.LatLngBounds();
var shopMarker = new google.maps.Marker({
position : new google.maps.LatLng(sessionStorage
.getItem('longitude'), sessionStorage
.getItem('latitude')),
map : map,
icon : image
});
bounds.extend(shopCoord);
bounds.extend(locCoord);
console.log(shopCoord);
map.fitBounds(bounds);
},
}
});
shopsDetailsPage.setItems(map);
}
The log logs the right coordinates.
The map shows this:
click here to see the map
but my wish is like this:
click here to see my wish
I dont know what to do, i mean im searching for an solution since hours, but every solution in the net isnt working in my application..
Anyone have any idea what I'm doing wrong?
I hope im posting every information you need to help my weak development experience ;)
This looks to me like you've got latitude and longitude the wrong way round:
var shopCoord = new google.maps.LatLng(sessionStorage
.getItem('longitude'), sessionStorage
.getItem('latitude'));
And again here:
var shopMarker = new google.maps.Marker({
position : new google.maps.LatLng(sessionStorage
.getItem('longitude'), sessionStorage
.getItem('latitude')),
map : map,
icon : image
});
If this is the case (and you've not just mis-labelled the variables in your 'sessionStorage' object) then this will affect the bounds, which is possibly the problem.
Got the Answer.
Thanks for everyone.
The Problem was, that
useCurrentLocation : {
autoUpdate : false
},
automatically centers the locationMarker.
I solved ist by using the html5 geolocation without the sencha touch implemented location method.
Thanks for helping guys!
Related
I am trying to simply click a point on a terrain to get its 3D coordinates but I cannot get this to work in the Cesium sandcastle:
var viewer = new Cesium.Viewer('cesiumContainer', {
terrainProvider : Cesium.createWorldTerrain()
});
var scene = viewer.scene;
scene.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(2.3488, 48.8534, 450),
orientation: {
heading: Cesium.Math.toRadians(0),
pitch: Cesium.Math.toRadians(-40),
},
});
var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
handler.setInputAction(function onLeftClick(movement) {
var ray = scene.camera.getPickRay(movement.position);
var pos = scene.globe.pick(ray, scene);
console.log("pos: ", pos);
}, Cesium.ScreenSpaceEventType.LEFT_CLICK
);
The function get executed on each click but the result is actually empty.
How could I get the terrain coordinates on a left click?
Example is inspired from: https://cesium.com/docs/cesiumjs-ref-doc/Globe.html#pick and https://cesium.com/docs/tutorials/cesium-workshop/
Why is your result empty?
Because console.log does not work as you expect in Sandcastle.
Please try to change "console.log("pos: ", pos);" to "console.log(pos);"
Is it possible to use console.log("pos: ", pos); but only within an inspect mode of a browser.
So, instead of using the default Sandcastle console, use the console in inspect mode (e.g., in Chrome or Firefox).
I have added Google Maps for Flutter
i know how to add a marker as it is given clearly in there examples
MarkerOptions _options = new MarkerOptions(
position: LatLng(
driver_lat,
driver_lng,
),
infoWindowText:
const InfoWindowText('An interesting location', '*'));
Marker marker = new Marker('1', _options);
//Adding Marker
googleMapController.addMarker(_options);
And i am removing the marker like below
googleMapController.removeMarker(marker);
for adding the marker it is taking MarkerOptions object as a parameter but for removing the marker it is asking for Marker object as parameter and my removing marker code is not working.
i am getting the below error
Failed assertion: line 201 pos 12: '_markers[marker._id] == marker': is not true.
There are two ways to do this, one is via clearMarkers() Method
mapController.clearMarkers();
Another one is via targeting each marker returned by mapController.markers
mapController.markers.forEach((marker){
mapController.removeMarker(marker);
});
2020 answer:
.clearMarkers() has been deprecated as now each Marker is a Widget stored in a map. The correct way to clear all of the markers now on your Google Map is to set the state of of your marker Map to an empty map.
e.g.
...
onPressed: () {
setState(() {
gMapMarkers = {};
});
}
....
Use clearMarkers(). It will clear all markers in your map. So try googleMapController.clearMarkers();
I've came across this issue myself with the google_maps_library and the main cause of this issue '_markers[marker._id] == marker': is not true. is the fact that all GoogleMapsController methods return a Future, so this error is, let's say a concurrency issue since the method cals are async.
The correct way to add/remove a marker would be:
_testRemoveMarker() async {
Marker marker = await _mapController.addMarker(...markerOption..);
_mapController.removeMarker(marker);
}
_clearMarkersAndRead() async {
_mapController.clearMarkers().then((_) {
//TODO: add makrers as you whish;
});
}
So, if you do any operations with the markers add/remove/update, you should be sure that the previous operation that involved markers is completed.
If anyone still struggling with removing a specific marker try this method;
MarkerId id = MarkerId("Pickup");
//markers[id] = {} as Marker; clear all markers
markers.removeWhere((key, value) => key == id); //clear a specific marker
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 am using phonegap, jquerymobile the googlemap API to get my current position and to watch my position.
For this, when I lunch my map page, my position is shown with a marker and the marker move when I move.
Even if it works excpeted when I close my App (onPause).
Here is my code (you can tell me how I can perfect it :o) )
$('#home').live("pagebeforeshow", function() {
if($('#googleAPI').length != 0){
navigator.geolocation.getCurrentPosition(function(position){
//showMap('mapHome',position.coords.latitude, position.coords.longitude);// Canvas, lat, long
var latLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
// Google Map options
var myOptions = {
zoom: 17,
//zoomControl : 1,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP////ROADMAP, SATELLITE, HYBRID and TERRAIN
};
// Create the Google Map, set options
Tracking.mapy = new google.maps.Map(document.getElementById('mapHome'), myOptions);
//addMarker(position.coords.latitude,position.coords.longitude);
},
showError,
{
enableHighAccuracy : true,
maximumAge : 2000
//maximumAge:Infinity
});
}
})
$('#home').live("pageshow", function() {
// Place and move the marker regarding to my position and deplacement
if($('#googleAPI').length != 0){
//var track_id = "me";
Tracking.watch_id = navigator.geolocation.watchPosition(
// Success
function(position){
var lat = position.coords.latitude;
var long = position.coords.longitude;
var latLng = new Array();
latLng[0] = lat;
latLng[1] = long;
//Tracking.myCoordinates.push(lat,long);
Tracking.myCoordinates.push(latLng);
addMarker(lat, long);
},
// Error
showError,
{
frequency: 1000
});
console.log('HW : WatchPosition called. Id:' + Tracking.watch_id);
}else{
Alert.show('The map API has not been loaded. Check for connection and try again. (pagebeforeshow)');
}
})
$('#home').live("pagebeforehide", function() {
if($('#googleAPI').length != 0){
//track_id = "me";
// Stop tracking the user
if (Tracking.watch_id != null) {
navigator.geolocation.clearWatch(Tracking.watch_id);
console.log('HW : WatchPosition cancelled Id:' + Tracking.watch_id);
Tracking.watch_id = null;
}
//navigator.geolocation.clearWatch(Tracking.watch_id);
//Tracking.watch_id = null;
Tracking.myCoordinates = new Array();
}else{
Alert.show('The map API has not been loaded. Check for connection and try again. (pagebeforeshide)');
}
});
The problem is when I close my App, because I still need to be alert when I go outside of my geofence. Then, as lomg as I do not stop to watch my position, I need it to be watching even if I close my position or if I lunch another app.
Then I do not know how to do when I called that Phonegap even:
document.addEventListener('pause', onPause, false);
function onPause(){}
Should I simply relunch my watch code with a different watch_id?
Any suggestion?
Many thank and happy new year
I think what you're trying to get at is running a background process using phonegap. The discussion in this link seems to say that it's only possible if you write a plugin to perform that functionality. PhoneGap doesn't have an API to do it out of the box.
Executing javascript in background using phonegap
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"
});
}