GoogleMapsEvent vs google.maps.event - google-maps

I am in the process of upgrading from Ionic 2 beta to RC3. In doing so, I also update the version of Google Maps to "google-maps": "^3.2.1". The Change in Google Maps, is that now it uses a GoogleMap object instead of google.maps.Map (see here).
I have been using google.maps.event., but now need to update it to use GoogleMapsEvent (I think). Because I get the following error on ionic serve:
Cannot find name 'google'.
google.maps.event.addListenerOnce(that.map, 'bounds_changed', function (event) {
let position: CameraPosition = that.map.getCameraPosition();
let zoom: number = position.zoom;
setTimeout(function () {
// let center: GoogleMapsLatLng = that.map.getCenter();
google.maps.event.trigger(that.map, 'resize');
// that.map.setCenter(center);
that.map.setZoom(zoom);
}, 100);
});
But GoogleMapsEvent does not have a addListenerOnce or trigger method.
Question
How do I update the code above to use GoogleMapsEvent instead of google.maps.event?
Thanks

From the documentation, this is how you can add eventlisteners.
// create a new map by passing HTMLElement
let element: HTMLElement = document.getElementById('map');
let map = new GoogleMap(element);
// listen to MAP_READY event
map.one(GoogleMapsEvent.MAP_READY).then(() => console.log('Map is ready!'));

Related

Titanium Alloy - How to run procedure after screen created

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

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 map v3 how fitbounds with zoom on user's location

I am using google v3, i want to fitbounds with center on userPinLoc object, i have the following code
var bounds = new google.maps.LatLngBounds();
bounds.extend(userPinLoc)// wants to center on userPinLocation
for (i in nearestEntitiesToZoom) {
entity = nearestEntitiesToZoom[i];
var googleLatLng = new google.maps.LatLng(entity.latitude,entity.longitude);
bounds.extend(googleLatLng);
}
bounds.extend(userPinLoc);
//googleMap.setCenter(userPinLoc) this not working
googleMap.fitBounds(bounds);
any quick fix after update i am pasting new code
function setInitialZoom() {
mapZoom = googleMap.getZoom();
var bounds = new google.maps.LatLngBounds();
bounds.extend(userPinLoc);
for (i in nearestEntitiesToZoom) {
entity = nearestEntitiesToZoom[i];
var googleLatLng = new google.maps.LatLng(entity.latitude,entity.longitude);
bounds.extend(googleLatLng);
}
google.maps.event.addDomListener(googleMap, 'bounds_changed', function() {
googleMap.setCenter(userPinLoc);
});
googleMap.fitBounds(bounds);
setTimeout(function() {
google.maps.event.clearListeners(googleMap, 'bounds_changed');
}, 3000);
}
Remove the setCenter from where it is currently. You need to have an event listener for when the map's bounds change. I think when you call fitBounds, you have to wait for it to redraw before you can adjust the centre. One way would be to use a timeout, but you can simply add this to your initialize function:
google.maps.event.addDomListener(googleMap, 'bounds_changed', updateCenter);
And then create a new function to update the centre, which takes the userPinLoc value (needs to be a global variable):
function updateCenter() {
googleMap.setCenter(userPinLoc);
}

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.

Google Map Click Event Issue with Kohana PHP

So this gets auto generated through the controller and I think I'm just overlooking something but the output is just like this
google.load("maps", "2.x", {"language" : "en"});
function initialize() {
if (GBrowserIsCompatible()) {
// Initialize the GMap
var map = new google.maps.Map2(document.getElementById("map"));
map.addControl(new google.maps.SmallMapControl());
map.setCenter(new google.maps.LatLng(30.226632, -97.935056), 10, G_NORMAL_MAP);
// Build custom marker icons
var tinyIcon = new google.maps.Icon();
tinyIcon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
tinyIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
tinyIcon.iconSize = new google.maps.Size(12,20);
tinyIcon.shadowSize = new google.maps.Size(22,20);
tinyIcon.iconAnchor = new google.maps.Point(6,20);
tinyIcon.infoWindowAnchor = new google.maps.Point(5,1);
// Show map points
var m1 = new google.maps.Marker(new google.maps.LatLng(35.2602340, -93.7939480), {icon:tinyIcon,bouncy:1});
google.maps.Event.addListener(m1, "click", function()
{
m1.openInfoWindowHtml(
'1<br />test,TX'
);
});
map.addOverlay(m1);
var m2 = new google.maps.Marker(new google.maps.LatLng(35.2810510, -93.8246510), {icon:tinyIcon,bouncy:1});
google.maps.Event.addListener(m2, "click", function()
{
m2.openInfoWindowHtml(
'test<br />test,Texas'
);
});
map.addOverlay(m2);
}
google.setOnLoadCallback(initialize);
So when i go to use a trigger event
google.maps.event.trigger(markers[m3], 'click');
Nothing happens, and I cant figure out the correct trigger to make it do so...
Based on the code sample you posted there is no markers[m3] defined, wouldn't you need to use google.maps.event.trigger(m2, 'click'); ? (m3 isn't defined at all in that code sample)