Error with Geocode API in Ionic 2 - google-maps

I’m using the Google Maps Geocode API to read an address and place a marker on the map. This is how I’m using it :
for(let marker of markers){
this.geocoder = new google.maps.Geocoder();
this.geocoder.geocode({
'address': marker["address"]
}, (results,status) => {
var position = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng()); // error pointing to this line
this.personMarker = new google.maps.Marker({position: position, title: marker.name, markerInfo: marker, map : this.map , icon : marker.imageurl});
google.maps.event.addListener(this.personMarker, 'click', () => {
this.showCard = true;
this.org = marker.organization;
this.gig = marker.gig;
this.location = marker["address"];
this.image = marker.imageurl;
this.ngoData = marker;
this.ownerusername = marker.ownerusername;
});
});
}
I get this error: ‘Cannot read property ‘0’ of null’ pointing to the line I’ve shown with a comment in the code snippet.Just don’t know what’s causing that error because I’m accessing the ‘results’ parameter only inside the callback. console.log(results) sometimes returns 'null' for the first iteration of the loop, followed by proper results for the rest of the iterations, or proper results for all iterations. I don't understand this inconsistent behavior, but I do know that I get this error usually when the intervals between me clicking and loading the map again is short.
I know that all the addresses are valid because sometimes all my markers appear on the map and the error doesn't turn up

Related

Remove marker in google_maps_flutter

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

Google maps how to force marker on the nearest road

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...

Ignore hidden features returned by identifyTask

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);
}
});
}

How can watch my position when I close my App with Phonegap and jquerymobile

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

Google Maps v3 OverlayView.getProjection()

I cannot seem to figure out why the object returned by getProjection() is undefined. Here is my code:
// Handles the completion of the rectangle
var ne = recBounds.getNorthEast();
var sw = recBounds.getSouthWest();
$("#map_tools_selat").attr( 'value', sw.lat() );
$("#map_tools_nwlat").attr( 'value', ne.lat() );
$("#map_tools_selng").attr( 'value', ne.lng() );
$("#map_tools_nwlng").attr( 'value', sw.lng() );
// Set Zoom Level
$("#map_tools_zoomlevel").attr( 'value', HAR.map.getZoom()+1 );
document.getElementById("map_tools_centerLat").value = HAR.map.getCenter().lat();
document.getElementById("map_tools_centerLong").value = HAR.map.getCenter().lng();
// All this junk below is for getting pixel coordinates for a lat/lng =/
MyOverlay.prototype = new google.maps.OverlayView();
MyOverlay.prototype.onAdd = function() { }
MyOverlay.prototype.onRemove = function() { }
MyOverlay.prototype.draw = function() { }
function MyOverlay(map) { this.setMap(map); }
var overlay = new MyOverlay(HAR.map);
var projection = overlay.getProjection();
// END - all the junk
var p = projection.fromLatLngToContainerPixel(recBounds.getCenter());
alert(p.x+", "+p.y);
My error is: Cannot call method 'fromLatLngToContainerPixel' of undefined
Actually, i the reason why this happens is because the projection object is created after the map is idle after panning / zooming. So, a better solution is to listen on the idle event of the google.maps.Map object, and get a reference to the projection there:
// Create your map and overlay
var map;
MyOverlay.prototype = new google.maps.OverlayView();
MyOverlay.prototype.onAdd = function() { }
MyOverlay.prototype.onRemove = function() { }
MyOverlay.prototype.draw = function() { }
function MyOverlay(map) { this.setMap(map); }
var overlay = new MyOverlay(map);
var projection;
// Wait for idle map
google.maps.event.addListener(map, 'idle', function() {
// Get projection
projection = overlay.getProjection();
})
I kind of figured out what was going on. Even though it is still not crystal clear why this happens, I know that I had to instantiate the variable "overlay" right after instantiating my google map (HAR.map). So I practically moved that code snippet into my HAR class and now i use:
HAR.canvassOverlay.getProjection().fromLatLngToContainerPixel( recBounds.getCenter() );
So now, every time I create a map via my class "HAR" I also have a parallel OverlayView object within my class.
The Error could have been with losing scope of my class object, but I think it was more of the map event "projection_changed" not being fired. I got a hint from the map API docs for map class, under method getProjection():
"Returns the current Projection. If the map is not yet initialized (i.e. the mapType is still null) then the result is null. Listen to projection_changed and check its value to ensure it is not null."
If you are getting the similar issue, make sure that you assign your overlayView.setMAP( YOUR_MAP_OBJECT ) closely after instantiating the map object.