i'm able to get GoogleMap on my Android device , the problem is it is not pointing to my current location.
I have installed these 2 packages:
$ ionic cordova plugin add cordova-plugin-googlemaps --variable API_KEY_FOR_ANDROID="YOUR_ANDROID_API_KEY_IS_HERE" --variable API_KEY_FOR_IOS="YOUR_IOS_API_KEY_IS_HERE"
$ npm install --save #ionic-native/google-maps
below is how my google map looks on my android device
below is my code:
ionViewDidLoad() {
console.log('ionViewDidLoad GoogleMapTestPage');
this.loadMap();
}
ngAfterViewInit() {
//this.loadMap();
}
loadMap() {
// create a new map by passing HTMLElement
let element: HTMLElement = document.getElementById('map');
let map: GoogleMap = this.googleMaps.create(element);
// listen to MAP_READY event
// You must wait for this event to fire before adding something to the map or modifying it in anyway
map.one(GoogleMapsEvent.MAP_READY).then(
() => {
console.log('Map is ready!');
// Now you can add elements to the map like the marker
}
);
// create LatLng object
let ionic: LatLng = new LatLng(43.0741904,-89.3809802);
// create CameraPosition
let position: any = {
target: ionic,
zoom: 18,
tilt: 30
};
// move the map's camera to position
map.moveCamera(position);
// create new marker
let markerOptions: MarkerOptions = {
position: ionic,
title: 'Ionic'
};
const marker:any = map.addMarker(markerOptions)
.then((marker: Marker) => {
marker.showInfoWindow();
});
}
my html code
<ion-content>
<div #map id="map" style="height:100%;"></div>
</ion-content>
My Question:
how to point to my current location in the above code!!
please help me as I am new to ionic 3, just I wanted to point to users current
location on google !!
You need to make changes on the map like adding marker once it is ready. So move the marker setting code to map.one(GoogleMapsEvent.MAP_READY).
let ionic: LatLng = new LatLng(43.0741904,-89.3809802);
// create CameraPosition
let position: any = {
target: ionic,
zoom: 18,
tilt: 30
};
map.one(GoogleMapsEvent.MAP_READY).then(
() => {
console.log('Map is ready!');
// Now you can add elements to the map like the marker
map.moveCamera(position);
// create new marker
let markerOptions: MarkerOptions = {
position: ionic,
title: 'Ionic'
};
const marker:any = map.addMarker(markerOptions)
.then((marker: Marker) => {
marker.showInfoWindow();
});
}
}
);
Try this and declare variable map:GoogleMap; before constructor after class. So you can reuse your map without render map more and more .Because every single load page your google map api quota is increasing .
My suggestion :
Put loading map on provider
this.map.one(GoogleMapsEvent.MAP_READY).then(()=>{
console.log("Map ready");
this.map.setMyLocationEnabled(true);
this.map.getMyLocation({enableHighAccuracy:true}).then(pos=>{
this.map.setCameraTarget(pos.latLng);
this.map.animateCamera({
target:pos.latLng
});
this.map.addMarker({
title: 'You',
icon: 'pin'
animation: 'DROP',
position: pos.latLng
}).then((marker)=>{
this.userMarker = marker;
marker.setPosition(pos.latLng);
});
});
});
For add marker you have to add marker on your map object with lat&lng and title.
have look:
map.addMarker(new MarkerOptions().position(new LatLng(22.7253, 75.8655)).title("Title"));
Happy coding!!
Firstly make sure your API Key is valid and add this into your manifest ``
Then use add map.setMyLocationEnabled(true) inside the onMapReady(GoogleMap map) method. like this
#Override
public void onMapReady(GoogleMap gMap) {
mGoogleMap = gMap;
mGoogleMap.setMyLocationEnabled(true);
buildGoogleApiClient();
mGoogleApiClient.connect();
}
Related
I'm working on an android project. I want to add a map about the museum the user wants to get information about. The region marked on this map should show the location of that museum. But in the code I wrote below, latitude and longitude data only belong to a museum. But I want to get latitude and longitude information from SQLITE and define it for all museums.
This is the code snippet:
LatLng _center = LatLng(36.54371283052991, 31.98871188028454);
Completer<GoogleMapController> _controller = Completer();
void _onMapCreated(GoogleMapController controller) {
_controller.complete(controller);
}
final Set<Marker> _markers = {};
void onAddMarkerButtonPressed() {
setState(() {
_markers.add(Marker(
markerId: MarkerId("111"),
position: _center,
icon: BitmapDescriptor.defaultMarker,
));
});
}
#override
void initState() {
checkconnection.checkConnection();
onAddMarkerButtonPressed();
super.initState();
}
This is the screenshot of my android project:
And, this is the DB Browser for SQLite :
I hope you can help me.
You can take a look this package 'geocoding'.
https://pub.dev/packages/geocoding
I hope it works.
I spent a lot of time trying to figure this out.
I have a map on my application and this map loads the actual location once it is loaded.
For some reason on my viewer (using Ionic Viewer) it works on my local device and on my localhost, but When I test it on my iPhone directly from Xcode, the map don't load.
If I compile an .apk and test it on android, the map don't load either.
.controller('mapaCtrl', function($scope, $compile, $location) {
$scope.goPayment = function() {
$location.path('side-menu/history');
};
var myLatlng = new google.maps.LatLng(34.603711, -58.381585);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
navigator.geolocation.getCurrentPosition(function(pos) {
map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
var myLocation = new google.maps.Marker({
position: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude),
map: map,
title: "My Location"
});
google.maps.event.addListener(myLocation, 'click', function() {
infowindow.open(map,myLocation);
});
});
var contentString = "<div><a ng-click='clickTest()'>Pagar Aqui!</a></div>";
var compiled = $compile(contentString)($scope);
var infowindow = new google.maps.InfoWindow({
content: compiled[0]
});
$scope.map = map;
$scope.clickTest = function() {
$location.path('side-menu/pay');
};
})
Any clue?
There may be several things affecting the proper functionality of your app, consider the following:
There could be an issue where the requests to google maps are blocked. Check out the whitelist plugin: https://stackoverflow.com/a/29896923/1956540
Try adding geoLocation permissions, here is an article I found that walks you through the whole thing: http://www.gajotres.net/using-cordova-geoloacation-api-with-google-maps-in-ionic-framework/
It is also important to wrap geolocation code into Ionic deviceready
event, execution will timeout without it:
ionic.Platform.ready(function() {
// Code goes here
}
I'm not sure it's necessary to have these anymore but I know for Android you could verify the permissions needed to exist in AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
There is probably some iOS equivalent that you can search for but I think installing the plugin should work on its own.
--
I am developing an ionic app to be run on Android. On a particular screen, I have a google maps and a search box. I have used the phone gap plugin for the google maps to get the native map instead of using Google Maps Javascript API as it is too slow.
The search box is autocomplete to get places from google using the following code -
input = document.getElementById 'search-input'
autocomplete = new google.maps.places.Autocomplete(input)
This turns the input field with autocomplete for places from google. The problem is that I am not able to select any of the options from the autocomplete dropdown.
My HTML code -
<ion-content scroll="false">
<div id="searchBox">
<input id="search-input">
</div>
<div id="map-canvas">
</ion-content>
The map-canvas holds the map. I tried adding ng-focus="disableTap()" to input search-input.
disableTap = ->
container = document.getElementsByClassName 'pac-container'
angular.element(container).attr 'data-tap-disabled', 'true'
angular.element(container).on 'click', ->
document.getElementById('search-input').blur()
I found this solutions at this link
But this does not work. Any inputs here? I'm at my wits end here.
The below worked for me.
From user #TillaTheHun0 :
.controller('MyCtrl', function($scope) {
$scope.disableTap = function(){
container = document.getElementsByClassName('pac-container');
// disable ionic data tab
angular.element(container).attr('data-tap-disabled', 'true');
// leave input field if google-address-entry is selected
angular.element(container).on("click", function(){
document.getElementById('searchBar').blur();
});
};
})
Okay i found the solution, this will make you able to select on mobile
add this after creating your map
$$('body').on('touchstart','.pac-container', function(e){
e.stopImmediatePropagation();
})
i will also post my full code in case you're confused :
var myLatLng = {lat: 36.5802466, lng: 127.95776367};
document.getElementById('qkp-lat').value = myLatLng.lat;
document.getElementById('qkp-lng').value = myLatLng.lng;
window.postmap = new google.maps.Map(document.getElementById('postmap'), {
center: myLatLng,
zoom: 6,
mapTypeControl: false,
streetViewControl: false,
disableDefaultUI: true,
mapTypeId: 'roadmap'
});
// GOOGLE MAP RESPONSIVENESS
google.maps.event.addDomListener(window, "resize", function() {
var center = postmap.getCenter();
google.maps.event.trigger(postmap, "resize");
postmap.setCenter(center);
});
//MARKER
window.PostAdMarker = new google.maps.Marker({
map: postmap,
position:myLatLng,
draggable: true,
anchorPoint: new google.maps.Point(0, -29)
});
//LOAD FROM CURRENT CITY
var geocoder = new google.maps.Geocoder();
//AFTER DRAG AND DROP SHOWS THE LAT AND LONG
google.maps.event.addListener(PostAdMarker, 'dragend', function (event) {
var latlng = {lat: this.getPosition().lat(), lng: this.getPosition().lng()};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[1]) {
// saving to dom
document.getElementById('qkp-lat').value = latlng.lat;
document.getElementById('qkp-lng').value = latlng.lng;
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
});
var getlocDiv = document.createElement('div');
var getlocvar = new getloc(getlocDiv, postmap);
getlocDiv.index = 1;
postmap.controls[google.maps.ControlPosition.TOP_RIGHT].push(getlocDiv);
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
postmap.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
postmap.addListener('bounds_changed', function() {
searchBox.setBounds(postmap.getBounds());
});
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: postmap,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
postmap.fitBounds(bounds);
});
$$('body').on('touchstart','.pac-container', function(e){
e.stopImmediatePropagation();
})
I have an android application in phonegap , it's a google maps , it shows me my current location , i have a draggable marker in my position and an infoWindow showing my latitude and my longitude.
var map;
var marker;
var infowindowPhoto = new google.maps.InfoWindow();
var latPosition;
var longPosition;
function initialize() {
var mapOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(10,10)
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
initializeMarker();
}
function initializeMarker() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
latPosition = position.coords.latitude;
longPosition = position.coords.longitude;
marker = new google.maps.Marker({
position: pos,
draggable: true,
animation: google.maps.Animation.DROP,
map: map
});
map.setCenter(pos);
updatePosition();
google.maps.event.addListener(marker, 'click', function (event) {
updatePosition();
});
google.maps.event.addListener(marker, 'dragend', function (event) {
updatePosition();
});
});
}
}
function updatePosition() {
latPosition = marker.getPosition().lat();
longPosition = marker.getPosition().lng();
contentString = '<div id="iwContent">Lat: <span id="latbox">' + latPosition + '</span><br />Lng: <span id="lngbox">' + longPosition + '</span></div>';
infowindowPhoto.setContent(contentString);
infowindowPhoto.open(map, marker);
}
initialize();
http://jsfiddle.net/upsidown/d3toa81m/
My problem that I want to show my address instead of my latitude and my longitude in my infoWindow. I find this tutorial https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse . My problem with this tutorial that i don't want to add this:
<input id="latlng" type="text" value="40.714224,-73.961452">
<input type="button" value="Reverse Geocode" onclick="codeLatLng()">
and if I don't add this the function "codeLatLng()" doesn't work. What should I do to show my address in my infowindow.
you are getting the grid coordinate from google maps. Once you get the grid, have you tried to use curl to scrap google maps for the city and state? I am about to do the same thing, good luck.
I used to use the native Android map on my applications, however, i've read that it is better to use Maps API V3, so i have read the docs but the problem is i don't know how to implement it in JAVA code(That's JavaScript). I want to add an overlay in my map, here is JS code:
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var myOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title:"Hello World!"
});
// To add the marker to the map, call setMap();
marker.setMap(map);
The question is how to implement it in JAVA/Android?
Thank you vrey much.