当我在Ionic应用程序中成功登录后尝试加载地图页面时,该页面正常加载,但是即使用户已通过身份验证,我也无法写入和读取Firebase实时数据库。
这些是我的实时数据库规则:
{
"rules": {
".read": "auth != null",
".write": "auth !=null",
}
}
这是我的
map.page.ts
import {
Component,
OnInit,
ViewChild,
ElementRef,
Input,
Renderer2,
OnDestroy,
} from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { environment } from "src/environments/environment";
import { Plugins, Capacitor } from "@capacitor/core";
import { Coordinates } from "../profile/location.model";
import * as firebase from "firebase/app";
import "firebase/database";
import { AuthService } from "../auth/auth.service";
import { take } from "rxjs/operators";
import { Platform } from "@ionic/angular";
@Component({
selector: "app-map",
templateUrl: "./map.page.html",
styleUrls: ["./map.page.scss"],
})
export class MapPage implements OnInit, OnDestroy {
@ViewChild("map", { static: false }) mapElementRef: ElementRef;
@Input() center = { lat: 34.2541, lng: 6.589 };
googleMaps: any;
isLoading: boolean;
ref = firebase.database().ref("geolocations/");
selectedLocationImage: any;
locationPick: any;
http: HttpClient;
alertCtrl: any;
markers = [];
map: any;
circle: any;
uid: any;
watch: string;
constructor(
private renderer: Renderer2,
private authService: AuthService,
public platform: Platform
) {}
ngOnInit() {
this.authService.userId.pipe(take(1)).subscribe((uid) => {
this.uid = uid;
console.log("uid : ", uid);
this.initMap();
this.ref.on("value", (resp) => {
this.deleteMarkers();
snapshotToArray(resp).forEach((data) => {
if (data.uid !== this.uid) {
let updatelocation = new this.googleMaps.LatLng(
data.latitude,
data.longitude
);
this.addCustomMarker(updatelocation);
this.setMapOnAll(this.map);
} else {
let updatelocation = new this.googleMaps.LatLng(
data.latitude,
data.longitude
);
this.addMarker(updatelocation);
this.setMapOnAll(this.map);
}
});
});
});
}
ngOnDestroy() {
this.clearWatch();
this.deleteMarker(this.uid);
}
initMap() {
if (!Capacitor.isPluginAvailable("Geolocation")) {
this.showErrorAlert();
return;
}
const { Plugins } = Capacitor;
Plugins.Geolocation.getCurrentPosition()
.then((geoPosition) => {
const myPosition = {
lat: geoPosition.coords.latitude,
lng: geoPosition.coords.longitude,
};
this.getGoogleMaps().then((googleMaps) => {
this.googleMaps = googleMaps;
const mapEl = this.mapElementRef.nativeElement;
const mylocation = new this.googleMaps.LatLng(myPosition);
this.map = new this.googleMaps.Map(this.mapElementRef.nativeElement, {
center: mylocation,
});
this.renderer.addClass(mapEl, "visible");
this.circle = new this.googleMaps.Circle({
strokeColor: "#989898",
strokeOpacity: 0.8,
strokeWeight: 1,
fillColor: "#989898",
fillOpacity: 0.35,
map: this.map,
center: mylocation,
radius: 1700000,
});
const bounds = this.circle.getBounds();
this.map.fitBounds(bounds);
this.watch = Plugins.Geolocation.watchPosition(
{ maximumAge: 0, timeout: 5000 },
(geoPosition, err) => {
let lastlatlng: Coordinates = {
lat: geoPosition.coords.latitude,
lng: geoPosition.coords.longitude,
};
this.deleteMarkers();
this.updateGeolocation(this.uid, lastlatlng);
let updatelocation = new this.googleMaps.LatLng(lastlatlng);
this.addMarker(updatelocation);
this.setMapOnAll(this.map);
this.circle.setCenter(lastlatlng);
//this.map.setCenter(lastlatlng);
}
);
});
})
.catch((err) => {
console.log(err);
});
}
clearWatch() {
if (this.watch != null) {
Plugins.Geolocation.clearWatch({ id: this.watch });
}
}
private showErrorAlert() {
this.alertCtrl
.create({
header: "Could not fetch location",
message: "Please use the map to pick a location!",
buttons: ["Okay"],
})
.then((alertEl: { present: () => any }) => alertEl.present());
}
private getGoogleMaps(): Promise<any> {
const win = window as any;
const googleModule = win.google;
if (googleModule && googleModule.maps) {
return Promise.resolve(googleModule.maps);
}
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src =
"https://maps.googleapis.com/maps/api/js?key=" +
environment.googleMapsAPIKey;
script.async = true;
script.defer = true;
document.body.appendChild(script);
script.onload = () => {
const loadedGoogleModule = win.google;
if (loadedGoogleModule && loadedGoogleModule.maps) {
resolve(loadedGoogleModule.maps);
} else {
reject("Google maps SDK not available.");
}
};
});
}
addMarker(location: Coordinates) {
const icon = {
url: "assets/icon/blue-dot.png",
scaledSize: new this.googleMaps.Size(26, 26),
};
const marker = new this.googleMaps.Marker({
map: this.map,
icon: icon,
});
marker.setPosition(location);
this.markers.push(marker);
}
addCustomMarker(location: Coordinates) {
// const icon = {
// url: "assets/icon/greenpin.svg",
// scaledSize: new this.googleMaps.Size(50, 45),
// origin: new this.googleMaps.Point(-10, 0), // origin
// };
const marker = new this.googleMaps.Marker({
map: this.map,
});
marker.setPosition(location);
this.markers.push(marker);
}
setMapOnAll(map: any) {
for (var i = 0; i < this.markers.length; i++) {
this.markers[i].setMap(map);
}
}
clearMarkers() {
this.setMapOnAll(null);
}
deleteMarkers() {
this.clearMarkers();
this.markers = [];
}
deleteMarker(userId: string) {
this.ref
.orderByChild("uid")
.equalTo(userId)
.once("value")
.then((snapshot) => {
snapshot.forEach((childSnapshot) => {
this.ref.child(childSnapshot.key).remove();
});
});
}
updateGeolocation(uid: string, coordinates: Coordinates) {
if (localStorage.getItem("mykey")) {
firebase
.database()
.ref("geolocations/" + localStorage.getItem("mykey"))
.set({
uid: uid,
latitude: coordinates.lat,
longitude: coordinates.lng,
});
} else {
let newData = this.ref.push();
newData.set({
uid: uid,
latitude: coordinates.lat,
longitude: coordinates.lng,
});
localStorage.setItem("mykey", newData.key);
}
}
}
export const snapshotToArray = (snapshot: firebase.database.DataSnapshot) => {
let returnArr = [];
snapshot.forEach((childSnapshot: { val: () => any; key: any }) => {
let item = childSnapshot.val();
item.key = childSnapshot.key;
returnArr.push(item);
});
return returnArr;
};
当我加载地图页面时,出现以下错误:
将规则更改为: