Address (Reverse Geocoding) google maps - android

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.

Related

Google maps only showing first time my android app is installed

I can not give much information, I just followed the tutorial from https://developers.google.com/maps/documentation/javascript/overview#js_api_loader_package to show a basic map.
the code is working properly on browser.
As requested, the code that is not working on mobile device:
let position;
this.geolocalizationService.getCurrentPosition().then(
p => {
position = { lat: p.coords.latitude, lng: p.coords.longitude};
},
err => this.logger.err(`Error in poisition obtaining ${err}`)
);
const loader = new Loader({
apiKey: 'MY_API_KEY',
version: 'weekly'
});
loader.load().then(() => {
this.map = new google.maps.Map(document.getElementById('map'), {
center: position,
zoom: 10,
});
});
The geolocalization method is correctly returning the position of the device.

Why my marker is not pointed to my current location

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

Cannot select from Google places autocomplete

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

Google Maps API v3 in PhoneGap: Circle duplicating and drawing tangent line after move

(This is a split off from my other post I made, Google Maps API v3 in PhoneGap: markers not drawing properly after move) . I've been working on a Google Maps API 3 application on Android using PhoneGap. It should track the users location and mark the location with a marker and a circle around it. I had been developing this on Android 2.3 and it was working fine. I then upgraded to a phone with Android 4.x and it was still working well, I thought.
Then last week I began noticing Google Maps doing some strange things when I moved the Marker and Circle. It would seem to create a duplicate Marker and Circle instead of just moving them. In the other post, I got an answer for the Marker issue, but not for the Circle. Sometimes if I change zoom then the duplicate Circle seems to go away. But also, it occasionally draws some weird tangent line from the top. See images below.
I started noticing this shortly after I received an Android update on my phone to version 4.1.1. Not sure if that's related, I can't find any info about a problem.
I reduced the map and phonegap code to a pretty minimal sample and its still doing it. I'm pretty sure it isn't related to phonegap. I upgraded my phonegap to 2.2 anyway to be sure, but as expected it didn't help. Can anyone tell if I am doing something wrong when moving the circle?
One solution that I tried was to hide the circle before moving it and then show it again after I move it. That seemed to solve the duplicate and tangent issue, but it made the map flash, which is really annoying when you move it every 3 seconds or so. So that doesn't seem like an acceptable solution. Test code is below. Note that I removed my Google Maps API key in test code.
I've also learned that one way to get it to redraw correctly is to drag the map so that no part of any circle is visible. Then when I drag it back so that the circle is visible, it is redrawn as just one correct circle.
Thanks, Eric
<!DOCTYPE HTML>
<html>
<head>
<title>Marker Test</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html {height: 100%}
body {height: 100%; margin:0; padding:0}
#map_canvas {height: 100%}
</style>
<script type="text/javascript" charset="utf-8" src="js/phonegap.js"></script>
<script type="text/javascript" charset="utf-8" src="http://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE&sensor=true"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// globals
var watchID = null;
var map = null;
var myLocationMarker = null;
var searchCircle = null;
// PhoneGap is ready
//
function onDeviceReady() {
startGPS();
}
function onUnLoad() {
console.log("clearing watch " + watchID);
navigator.geolocation.clearWatch(watchID);
}
function startGPS() {
console.log("In startGPS");
var refreshMilliseconds = 5000;
var options = { frequency: refreshMilliseconds, enableHighAccuracy: true};
watchID = navigator.geolocation.watchPosition(onGPSSuccess, onGPSError, options);
// create Google map
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
myLocationMarker = new google.maps.Marker({
title: 'This is me!',
zIndex: 90,
optimized: false,
map:map
});
searchCircle = new google.maps.Circle({
fillColor: '#c0e4dd',
strokeColor: '#f15f22',
fillOpacity: 0.5,
radius: 1500,
map:map
});
}
var onGPSSuccess = function(p) {
// get the new coordinates
var lat = p.coords.latitude;
var lng = p.coords.longitude;
console.log("watch ID " + watchID);
// now that we have the coordinates, we can move the marker and circle on the Google Map
MoveMarkerAndCircle(lat, lng);
};
var MoveMarkerAndCircle = function(lat, lng) {
var myLocation = new google.maps.LatLng(lat, lng);
myLocationMarker.setPosition(myLocation);
// searchCircle.setVisible(false);
searchCircle.setCenter(myLocation);
// searchCircle.setVisible(true);
map.setCenter(myLocation);
}
var onGPSError = function() {
console.log("GPS Error");
};
var GenerateFakeMovement = function() {
var currentPosition = myLocationMarker.getPosition();
var newLat = currentPosition.lat() + 0.01;
var newLng = currentPosition.lng() + 0.01;
MoveMarkerAndCircle(newLat, newLng);
}
</script>
</head>
<body style="height:100%;text-align:center" onunload="onUnLoad()">
<div id="map_canvas" style="width: 100%;height:80%"></div>
MAKE FAKE MOVEMENT
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
<title>Marker Test</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html {height: 100%}
body {height: 100%; margin:0; padding:0}
#map_canvas {height: 100%}
</style>
<script type="text/javascript" charset="utf-8" src="http://maps.googleapis.com/maps/api/js?v=3&sensor=true"></script>
<script type="text/javascript" charset="utf-8">
var watchID = null;
var map = null;
var myLocationMarker = null;
var searchCircle = null;
function onDeviceReady() {
startGPS();
}
function onUnLoad() {
console.log("clearing watch " + watchID);
navigator.geolocation.clearWatch(watchID);
}
function startGPS() {
console.log("In startGPS");
var refreshMilliseconds = 5000;
var options = { frequency: refreshMilliseconds, enableHighAccuracy: true};
if(watchID ==null)
watchID = navigator.geolocation.watchPosition(onGPSSuccess, onGPSError, options);
// create Google map
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
myLocationMarker = new google.maps.Marker({
title: 'This is me!',
zIndex: 90,
optimized: false,
map:map
});
searchCircle = new google.maps.Circle({
fillColor: '#c0e4dd',
strokeColor: '#f15f22',
fillOpacity: 0.5,
radius: 1500,
map:map
});
}
var onGPSSuccess = function(p) {
// get the new coordinates
var lat = p.coords.latitude;
var lng = p.coords.longitude;
console.log("watch ID " + watchID);
// now that we have the coordinates, we can move the marker and circle on the Google Map
MoveMarkerAndCircle(lat, lng);
};
var MoveMarkerAndCircle = function(lat, lng) {
var myLocation = new google.maps.LatLng(lat, lng);
myLocationMarker.setPosition(myLocation);
// searchCircle.setVisible(false);
searchCircle.setCenter(myLocation);
// searchCircle.setVisible(true);
map.setCenter(myLocation);
}
var onGPSError = function() {
console.log("GPS Error");
};
function GenerateFakeMovement() {
var currentPosition = myLocationMarker.getPosition();
var newLat = currentPosition.lat() + 0.01;
var newLng = currentPosition.lng() + 0.01;
MoveMarkerAndCircle(newLat, newLng);
}
</script>
</head>
<body style="height:100%;text-align:center" onload="onDeviceReady()" onunload="onUnLoad()">
<div id="map_canvas" style="width: 100%;height:80%"></div>
MAKE FAKE MOVEMENT
</body>
</html>​
May not be entirely related to your problem, but if you bind a circle to a marker you don't have to set the circle position manually.
if (myMarker == undefined) {
myMarker = new google.maps.Marker({
position: mouseEvent.latLng,
title: 'My Position',
map: map,
draggable: true
});
var circle = new google.maps.Circle({
map: map,
radius: 100000, // 100 km
fillOpacity: 0.1,
strokeOpacity: 0.5,
strokeWeight: 1
});
circle.bindTo('center', myMarker, 'position'); //This will set the circle bound to the marker at center
}
So you only need to update the position of the marker.
Hope this helps.
I hope that I'm doing the right thing by posting this as an "answer". I still have the issue, but I have narrowed my own example down to the point that it seems clear it is an issue with Google Maps API v3 on Android 4.1.1 only. The code for the narrowed down test case is below and no longer involves PhoneGap.
I've posted the test page online here:
http://kcwebprogrammers.com/MarkerTest-NoGps.html
If you browse there in Windows (Chrome or IE) or with the Internet browser on Android 2.3, then moving the circle works just fine. If you browse to the same page with the Internet browser on Android 4.1.1, then you'll see that the original circle is still visible after the circle is moved, causing two circles. So I've posted the issue to the Google Maps issue list.
Thanks for the suggestions above. Please let me know if anyone thinks I should do anything different with this post.
<!DOCTYPE HTML>
<html>
<head>
<title>Marker Test</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html {height: 100%}
body {height: 100%; margin:0; padding:0}
#map_canvas {height: 100%}
</style>
<script type="text/javascript" charset="utf-8" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDTGR9VjM2t5ixumkk_jHg155s0C1S5g3Y&sensor=true"></script>
<script type="text/javascript" charset="utf-8">
// globals
var watchID = null;
var map = null;
var myLocationMarker = null;
var searchCircle = null;
var myLocation = null;
function onLoad() {
startGPS();
}
function onUnLoad() {
console.log("clearing watch " + watchID);
}
function startGPS() {
// simulate getting position from GPS
myLocation = new google.maps.LatLng(39, -90);
// create Google map
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center:myLocation
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.trigger(map, 'resize');
myLocationMarker = new google.maps.Marker({
title: 'This is me!',
zIndex: 90,
optimized: false,
map:map,
position: myLocation
});
searchCircle = new google.maps.Circle({
fillColor: '#c0e4dd',
strokeColor: '#f15f22',
fillOpacity: 0.5,
radius: 1500,
map:map,
center:myLocation
});
// using bindTo instead does not fix the problem
// searchCircle.bindTo('center', myLocationMarker, 'position'); //This will set the circle bound to the marker at center
}
var MoveMarkerAndCircle = function(lat, lng) {
myLocation = new google.maps.LatLng(lat, lng);
myLocationMarker.setPosition(myLocation);
// set circle invisible before moving and visible after does fix redraw for 4.1.1
// but causes some annoying flashing of the circle for 4.1.1 and everything else
// searchCircle.setVisible(false);
searchCircle.setCenter(myLocation);
// searchCircle.setVisible(true);
}
var GenerateFakeMovement = function() {
var currentPosition = myLocationMarker.getPosition();
var newLat = currentPosition.lat() + 0.001;
var newLng = currentPosition.lng() + 0.001;
MoveMarkerAndCircle(newLat, newLng);
}
</script>
</head>
<body style="height:100%;text-align:center" onunload="onUnLoad()" onload="startGPS()">
<div id="map_canvas" style="width: 100%;height:90%"></div>
MOVE MARKER AND CIRCLE
</body>
</html>

How to add overlay on Maps API V3?

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.

Categories

Resources