Reputation: 491
I wrote the following html/js
code which is working fine.
<!DOCTYPE html>
<html>
<head>
<script src = "https://maps.googleapis.com/maps/api/js"></script>
<script>
function loadMap() {
var lat = 1;
var lng = 0;
var pos = "x";
var mapOptions = {
center:new google.maps.LatLng(45.10,20.10),
zoom:5
}
var map = new google.maps.Map(document.getElementById("sample"),mapOptions);
var marker = new google.maps.Marker({
position: map.getCenter(),
icon: {
path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
scale: 5,
strokeWeight:2,
strokeColor:"#B40404"
},
draggable:true,
map: map,
});
google.maps.event.addListener(marker, 'dragend', function() {
lat = marker.getPosition().lat();
lng = marker.getPosition().lng();
pos = " - " + lat + " - " + lng + " - ";
infowindow = new google.maps.InfoWindow({
content: pos
});
infowindow.open(map,marker);
});
}
</script>
</head>
<body onload = "loadMap()">
<div id = "sample" style = "width:580px; height:400px;"></div>
</body>
</html>
As you can see I did not use any API key <script src = "https://maps.googleapis.com/maps/api/js">
, for me it is enough this kind of usage.
Second step of my developing is to use this code in my Ionic2 app. So I start trying to load a simple map in my app but I'm facing some issues.
My ionic2 project is with a tab template, and as a first step I set the following row in my src/index.html
<head>
...
<script src="https://maps.googleapis.com/maps/api/js"></script>
...
</head>
Then in my related page (SearchPage) I just inserted the following content in the html
file:
<ion-content>
<div #map id="map"></div>
</ion-content>
and the ts
file looks like this:
export class SearchPage {
@ViewChild('map') mapElement: ElementRef;
map: any;
...
text: any;
lat : any;
lon : any;
constructor(public navCtrl: NavController, public recoshService: Recosh, public alertCtrl: AlertController) {
Geolocation.getCurrentPosition().then(
pos => {
this.lat = pos.coords.latitude;
this.lon = pos.coords.longitude;
this.loadMap();
this.loadGuides();
},
err => {
.....
loadMap(){
let latLng = new google.maps.LatLng(this.lat, this.lon);
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
When Ionic2 is building errors are shown and the transpile fails. All of them are related the following error:
Cannot find name 'google'
It seems I'm using the js library in a wrong way. How can I fix it?
Upvotes: 1
Views: 4144
Reputation: 416
Just import the types for Google Maps:
npm i --save-dev @types/google.maps
Upvotes: 0
Reputation: 16327
I solved it by installing googlemaps:
$npm install @types/googlemaps --save-dev
Upvotes: 0
Reputation: 44659
That's just Typescript complaining about knowing nothing of what google
is. You can fix it by just declaring the property like this:
// imports ...
declare var google: any
@Component({
...
})
export class ....
Upvotes: 2