How to save result from Google Place Autocomplete - javascript

Firstly I would like to let you guys know that I have already checked many stack overflow Q&As, but I couldn't get the right solution.
I made a rails app by following the youtube.
https://www.youtube.com/watch?v=UtgwdLiJ5hA&t
It worked well including markerCluster which didn't cover in that youtube.
However, what I tried to add was that each user has his or her own search result(only the last one), and after hitting search button the page will be redirected to the same page with queries which have information about autocompleted place.
I succeeded in redirecting the same page with queries, but it was too hard to make the same map object as the one just after autocompleting.
The closest answer was as below, but it didn't work perfectly because AutocompleteService didn't return the first prediction as the place I wanted even though I put the exact address chosen just before redirecting.
How to set a default value for a Google places API auto complete textbox
The second trial was just copying some part of autocomplete object (bounds, location) and applying to the map object after redirecting. It seemed to work about only position, but the map display result has something wrong with boundary and the area seen.
The third trial was using place_id with the second trial, but I didn't think it would work.
I really wanted to insert the address text, select the address I chose before redirecting, and create autocomplete 'place_change' event AUTOMATICALLY as soon as the page was redirected. However, I have no idea how to do that.
Here is the main_map_controller.js (it is stimulus js)
import { Controller } from "stimulus"
export default class extends Controller {
// currentUrl is for redirecting to root_path in javascript
static targets = ["field", "map", "jsonMarkers", "currentUrl", "east", "north", "south", "west", "lat", "lng", "zoom"];
connect() {
if (typeof(google) != "undefined") {
this.initializeMap();
}
}
initializeMap() {
this._jason_locations = JSON.parse(this.jsonMarkersTarget.value);
this.map();
this.markerCluster();
this.autocomplete();
this.placeChanged();
// this.initialAutocomplete();
this.setPlace();
console.log('this.eastTarget.value:', this.eastTarget.value)
}
hasQuery() {
if (this.fieldTarget.value != "" && this.eastTarget.value != "" && this.northTarget.value != "" && this.southTarget.value != "" &&
this.westTarget.value != "" && this.latTarget.value != "" && this.lngTarget.value != "" && this.zoomTarget.value != ""
)
return true;
else
return false;
}
// Google map initialization
map() {
if (this._map == undefined) {
if (this.hasQuery())
{
this._map = new google.maps.Map(this.mapTarget, {
center: new google.maps.LatLng(
parseFloat(this.latTarget.value),
parseFloat(this.lngTarget.value)
),
zoom: 13
});
} else {
this._map = new google.maps.Map(this.mapTarget, {
center: new google.maps.LatLng(
0,
0
),
zoom: 13
});
}
// Try HTML5 geolocation
var cur_map = this._map;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
cur_map.setCenter({
lat: position.coords.latitude,
lng: position.coords.longitude
})
});
}
}
return this._map;
}
// markerCluster() make a group of markers
markerCluster() {
let current_map = this.map();
if (this._marker_cluster == undefined) {
var markers = this._jason_locations.map((location, i) => {
var marker = new google.maps.Marker({
position: {
lat: parseFloat(location["latitude"]),
lng: parseFloat(location["longitude"])
}
});
marker.addListener('click', () => {
let infoWindow = new google.maps.InfoWindow({
content: `<p>${location.address}</p>`
});
infoWindow.open(current_map, marker);
});
return marker;
});
this._marker_cluster = new MarkerClusterer(this.map(),
markers,
{imagePath: 'https://cdn.rawgit.com/googlemaps/js-marker-clusterer/gh-pages/images/m'}
);
}
return this._markers_cluster;
}
// Autocomplete function. It suggests the full address. 'formatted_address' was added to use user's bad behavior instead of
// using placeChanged(), but 'formatted_address' saved was not 100% same as the result address of autocomplete, so I didtn' use it.
// I don't understand why???
autocomplete() {
if (this._autocomplete == undefined) {
this._autocomplete = new google.maps.places.Autocomplete(this.fieldTarget);
this._autocomplete.bindTo('bounds', this.map());
this._autocomplete.setFields(['address_components', 'geometry', 'icon', 'name', 'formatted_address', 'place_id']);
this._autocomplete.addListener('place_changed', this.placeChanged.bind(this));
}
return this._autocomplete;
}
// If user typed strange word after autocomplete done, we should not allow to search with that word.
placeChanged() {
this._place_changed = this.fieldTarget.value;
}
// Because AutoComplete cannot have initial place, I had to use another class, AutocompleteService.
initialAutocomplete() {
if (this.fieldTarget.value == undefined || this.fieldTarget.value == "")
return;
let autocompleteService = new google.maps.places.AutocompleteService();
let request = { input: this.fieldTarget.value };
autocompleteService.getPlacePredictions(request, (predictionsArr, placesServiceStatus) => {
console.log('predictionArr:', predictionsArr);
console.log('placesServiceStatus:', placesServiceStatus);
let placeRequest = { placeId: predictionsArr[0].place_id };
let placeService = new google.maps.places.PlacesService(this.map());
placeService.getDetails(placeRequest, (placeResult, placeServiceStatus) => {
console.log('placeResult:', placeResult)
console.log('placeServiceStatus:', placeServiceStatus);
this.setPlace(placeResult);
});
});
}
// setPlace(placeResult) {
setPlace() {
// let place = this.autocomplete().getPlace();
// let place = placeResult;
if (!this.hasQuery()) {
return;
}
console.log('this.eastTarget.value:', this.eastTarget.value)
console.log('this.northTarget.value:', this.northTarget.value)
console.log('this.southTarget.value:', this.southTarget.value)
console.log('this.westTarget.value:', this.westTarget.value)
// let bound = {
// east: parseFloat(this.eastTarget.value),
// north: parseFloat(this.northTarget.value),
// south: parseFloat(this.southTarget.value),
// west: parseFloat(this.westTarget.value)
// }
// console.log('bounds:', bound)
// // this.map().fitBounds(place.geometry.viewport);
// // this.map().setCenter(place.geometry.location);
// this.map().fitBounds(bound);
// let bounds = this.map().getBounds();
// console.log('bounds:', bounds)
let bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(parseFloat(this.southTarget.value), parseFloat(this.westTarget.value)),
new google.maps.LatLng(parseFloat(this.northTarget.value), parseFloat(this.eastTarget.value))
);
this.map().fitBounds(bounds);
this.map().setCenter({
lat: parseFloat(this.latTarget.value),
lng: parseFloat(this.lngTarget.value)
});
let zoom = this.map().getZoom();
console.log('zoom:', zoom)
let center = this.map().getCenter();
console.log('center:', center)
document.getElementById("search-area").innerHTML = `Near ${this.fieldTarget.value}`;
this._jason_locations.forEach( location => {
var position = {
lat: parseFloat(location["latitude"]),
lng: parseFloat(location["longitude"])
}
console.log('position:', position)
if (bounds.contains(position)) {
document.getElementById(location["id"]).classList.remove("d-none")
} else {
document.getElementById(location["id"]).classList.add("d-none")
}
});
// this.latitudeTarget.value = place.geometry.location.lat();
// this.longitudeTarget.value = place.geometry.location.lng();
}
reloadMap() {
let place = this.autocomplete().getPlace();
console.log(place)
// this.setPlace(place);
if (place == undefined || this.fieldTarget.value == "" || this._place_changed != this.fieldTarget.value || !place.geometry) {
window.alert("Address is invalid!");
return;
}
this.map().fitBounds(place.geometry.viewport);
this.map().setCenter(place.geometry.location);
console.log('place.geometry.viewport:', place.geometry.viewport)
console.log('place.geometry.location:', place.geometry.location)
let bounds = this.map().getBounds();
console.log('bounds:', bounds)
let zoom = this.map().getZoom();
console.log('zoom:', zoom)
console.log('place.place_id:', place.place_id)
// This code was redirect root_path with query, but there was a problem that map was reloaded twice, so removed it.
// If adding query is not a solution for having each user's recent search history, then what else would it be?
let jsonParams = { "address": this.fieldTarget.value, ...bounds.toJSON(), ...place.geometry.location.toJSON(), "zoom": zoom.toString() };
const params = new URLSearchParams(jsonParams);
console.log(params.toString());
// Redirect to /posts/?address=xxxxx
console.log('params:', `${this.currentUrlTarget.value}/?${params.toString()}`);
window.location.href = `${this.currentUrlTarget.value}/?${params.toString()}`;
console.log('window.location.href:', window.location.href)
}
// prohibit Enter key, only allow to hit the search button.
preventSubmit(e) {
if (e.key == "Enter") {
e.preventDefault();
}
}
}

Yay, I finally figured it out by getting a hint from the following stack overflow site.
Google Maps map.getBounds() immediately after a call to map.fitBounds
What I fixed was modifying the second trial.
I didn't pass over the result of fitBounds() of autocomplete but viewport bounds of autocomplete itself, and after redirecting I wrapped the all codes after fitBounds() into the 'bound_changed' event handler with the help of the above solution.
Here is my fixed code, and it worked well. (Sorry about unused code and comment. I want to leave it for the record)
import { Controller } from "stimulus"
export default class extends Controller {
// currentUrl is for redirecting to root_path in javascript
static targets = ["field", "map", "jsonMarkers", "currentUrl", "east", "north", "south", "west", "lat", "lng"];
connect() {
if (typeof(google) != "undefined") {
this.initializeMap();
}
}
initializeMap() {
this._jason_locations = JSON.parse(this.jsonMarkersTarget.value);
this.map();
this.markerCluster();
this.autocomplete();
this.placeChanged();
// this.initialAutocomplete();
this.setPlace();
console.log('this.eastTarget.value:', this.eastTarget.value)
}
hasQuery() {
if (this.fieldTarget.value != "" && this.eastTarget.value != "" && this.northTarget.value != "" && this.southTarget.value != "" &&
this.westTarget.value != "" && this.latTarget.value != "" && this.lngTarget.value != ""
)
return true;
else
return false;
}
// Google map initialization
map() {
if (this._map == undefined) {
if (this.hasQuery())
{
this._map = new google.maps.Map(this.mapTarget, {
center: new google.maps.LatLng(
parseFloat(this.latTarget.value),
parseFloat(this.lngTarget.value)
)
// zoom: parseInt(this.zoomTarget.value)
});
} else {
this._map = new google.maps.Map(this.mapTarget, {
center: new google.maps.LatLng(
0,
0
),
zoom: 13
});
}
// Try HTML5 geolocation
var cur_map = this._map;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
cur_map.setCenter({
lat: position.coords.latitude,
lng: position.coords.longitude
})
});
}
}
return this._map;
}
// markerCluster() make a group of markers
markerCluster() {
let current_map = this.map();
if (this._marker_cluster == undefined) {
var markers = this._jason_locations.map((location, i) => {
var marker = new google.maps.Marker({
position: {
lat: parseFloat(location["latitude"]),
lng: parseFloat(location["longitude"])
}
});
marker.addListener('click', () => {
let infoWindow = new google.maps.InfoWindow({
content: `<p>${location.address}</p>`
});
infoWindow.open(current_map, marker);
});
return marker;
});
this._marker_cluster = new MarkerClusterer(this.map(),
markers,
{imagePath: 'https://cdn.rawgit.com/googlemaps/js-marker-clusterer/gh-pages/images/m'}
);
}
return this._markers_cluster;
}
// Autocomplete function. It suggests the full address. 'formatted_address' was added to use user's bad behavior instead of
// using placeChanged(), but 'formatted_address' saved was not 100% same as the result address of autocomplete, so I didtn' use it.
// I don't understand why???
autocomplete() {
if (this._autocomplete == undefined) {
this._autocomplete = new google.maps.places.Autocomplete(this.fieldTarget);
this._autocomplete.bindTo('bounds', this.map());
this._autocomplete.setFields(['address_components', 'geometry', 'icon', 'name']);
this._autocomplete.addListener('place_changed', this.placeChanged.bind(this));
}
return this._autocomplete;
}
// If user typed strange word after autocomplete done, we should not allow to search with that word.
placeChanged() {
this._place_changed = this.fieldTarget.value;
}
// Because AutoComplete cannot have initial place, I had to use another class, AutocompleteService.
initialAutocomplete() {
if (this.fieldTarget.value == undefined || this.fieldTarget.value == "")
return;
let autocompleteService = new google.maps.places.AutocompleteService();
let request = { input: this.fieldTarget.value };
autocompleteService.getPlacePredictions(request, (predictionsArr, placesServiceStatus) => {
console.log('predictionArr:', predictionsArr);
console.log('placesServiceStatus:', placesServiceStatus);
let placeRequest = { placeId: predictionsArr[0].place_id };
let placeService = new google.maps.places.PlacesService(this.map());
placeService.getDetails(placeRequest, (placeResult, placeServiceStatus) => {
console.log('placeResult:', placeResult)
console.log('placeServiceStatus:', placeServiceStatus);
this.setPlace(placeResult);
});
});
}
// setPlace(placeResult) {
setPlace() {
// let place = this.autocomplete().getPlace();
// let place = placeResult;
if (!this.hasQuery()) {
return;
}
console.log('this.eastTarget.value:', this.eastTarget.value)
console.log('this.northTarget.value:', this.northTarget.value)
console.log('this.southTarget.value:', this.southTarget.value)
console.log('this.westTarget.value:', this.westTarget.value)
// let bound = {
// east: parseFloat(this.eastTarget.value),
// north: parseFloat(this.northTarget.value),
// south: parseFloat(this.southTarget.value),
// west: parseFloat(this.westTarget.value)
// }
// console.log('bounds:', bound)
// // this.map().fitBounds(place.geometry.viewport);
// // this.map().setCenter(place.geometry.location);
// this.map().fitBounds(bound);
// let bounds = this.map().getBounds();
// console.log('bounds:', bounds)
let bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(parseFloat(this.southTarget.value), parseFloat(this.westTarget.value)),
new google.maps.LatLng(parseFloat(this.northTarget.value), parseFloat(this.eastTarget.value))
);
this.map().fitBounds(bounds);
google.maps.event.addListenerOnce(this.map(), 'bounds_changed', () => {
this.map().setCenter({
lat: parseFloat(this.latTarget.value),
lng: parseFloat(this.lngTarget.value)
});
bounds = this.map().getBounds();
console.log('bounds:', bounds)
let zoom = this.map().getZoom();
console.log('zoom:', zoom)
let center = this.map().getCenter();
console.log('center:', center)
document.getElementById("search-area").innerHTML = `Near ${this.fieldTarget.value}`;
this._jason_locations.forEach( location => {
var position = {
lat: parseFloat(location["latitude"]),
lng: parseFloat(location["longitude"])
}
console.log('position:', position)
if (bounds.contains(position)) {
document.getElementById(location["id"]).classList.remove("d-none")
} else {
document.getElementById(location["id"]).classList.add("d-none")
}
});
// this.latitudeTarget.value = place.geometry.location.lat();
// this.longitudeTarget.value = place.geometry.location.lng();
})
}
reloadMap() {
let place = this.autocomplete().getPlace();
console.log(place)
// this.setPlace(place);
if (place == undefined || this.fieldTarget.value == "" || this._place_changed != this.fieldTarget.value || !place.geometry) {
window.alert("Address is invalid!");
return;
}
// This code was redirect root_path with query, but there was a problem that map was reloaded twice, so removed it.
// If adding query is not a solution for having each user's recent search history, then what else would it be?
// let jsonParams = { "address": this.fieldTarget.value, ...bounds.toJSON(), ...place.geometry.location.toJSON(), "zoom": zoom.toString() };
let jsonParams = { "address": this.fieldTarget.value, ...place.geometry.viewport.toJSON(), ...place.geometry.location.toJSON()};
const params = new URLSearchParams(jsonParams);
// Redirect to /posts/?address=xxxxx
window.location.href = `${this.currentUrlTarget.value}/?${params.toString()}`;
}
// prohibit Enter key, only allow to hit the search button.
preventSubmit(e) {
if (e.key == "Enter") {
e.preventDefault();
}
}
}

Related

Problem getting my correct location with google chrome Javascript

I have the following code which is responsible for the geographical location of latitude, longitude and the map of where one is:
<html>
<head>
<title>javascript-mobile-desktop-geolocation With No Simulation with Google Maps</title>
<meta name = "viewport" content = "width = device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;">
<style>
body {font-family: Helvetica;font-size:11pt;padding:0px;margin:0px}
#title {background-color:#e22640;padding:5px;}
#current {font-size:10pt;padding:5px;}
</style>
</head>
<body onload="initialiseMap();initialise()">
<h1>location GPS</h1>
<div id="current">Initializing...</div>
<div id="map_canvas" style="width:320px; height:350px"></div>
<script src="js/geoPosition.js" type="text/javascript" charset="utf-8">
</script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function initialiseMap()
{
var myOptions = {
zoom: 4,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function initialise()
{
if(geoPosition.init())
{
document.getElementById('current').innerHTML="Receiving...";
geoPosition.getCurrentPosition(showPosition,function(){document.getElementById('current').innerHTML="Couldn't get location"},{enableHighAccuracy:true});
}
else
{
document.getElementById('current').innerHTML="Functionality not available";
}
}
function showPosition(p)
{
var latitude = parseFloat( p.coords.latitude );
var longitude = parseFloat( p.coords.longitude );
document.getElementById('current').innerHTML="latitude=" + latitude + " longitude=" + longitude;
var pos=new google.maps.LatLng( latitude , longitude);
map.setCenter(pos);
map.setZoom(14);
var infowindow = new google.maps.InfoWindow({
content: "<strong>yes</strong>"
});
var marker = new google.maps.Marker({
position: pos,
map: map,
title:"You are here"
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
</script>
</body>
</html>
the file geoPosition.js:
var bb = {
success: 0,
error: 0,
blackberryTimeoutId : -1
};
function handleBlackBerryLocationTimeout()
{
if(bb.blackberryTimeoutId!=-1) {
bb.error({ message: "Timeout error",
code: 3
});
}
}
function handleBlackBerryLocation()
{
clearTimeout(bb.blackberryTimeoutId);
bb.blackberryTimeoutId=-1;
if (bb.success && bb.error) {
if(blackberry.location.latitude==0 && blackberry.location.longitude==0) {
//http://dev.w3.org/geo/api/spec-source.html#position_unavailable_error
//POSITION_UNAVAILABLE (numeric value 2)
bb.error({message:"Position unavailable", code:2});
}
else
{
var timestamp=null;
//only available with 4.6 and later
//http://na.blackberry.com/eng/deliverables/8861/blackberry_location_568404_11.jsp
if (blackberry.location.timestamp)
{
timestamp = new Date( blackberry.location.timestamp );
}
bb.success( { timestamp: timestamp ,
coords: {
latitude: blackberry.location.latitude,
longitude: blackberry.location.longitude
}
});
}
//since blackberry.location.removeLocationUpdate();
//is not working as described http://na.blackberry.com/eng/deliverables/8861/blackberry_location_removeLocationUpdate_568409_11.jsp
//the callback are set to null to indicate that the job is done
bb.success = null;
bb.error = null;
}
}
var geoPosition=function() {
var pub = {};
var provider=null;
var u="undefined";
var ipGeolocationSrv = 'http://freegeoip.net/json/?callback=JSONPCallback';
pub.getCurrentPosition = function(success,error,opts)
{
provider.getCurrentPosition(success, error,opts);
}
pub.jsonp = {
callbackCounter: 0,
fetch: function(url, callback) {
var fn = 'JSONPCallback_' + this.callbackCounter++;
window[fn] = this.evalJSONP(callback);
url = url.replace('=JSONPCallback', '=' + fn);
var scriptTag = document.createElement('SCRIPT');
scriptTag.src = url;
document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
},
evalJSONP: function(callback) {
return function(data) {
callback(data);
}
}
};
pub.confirmation = function()
{
return confirm('This Webpage wants to track your physical location.\nDo you allow it?');
};
pub.init = function()
{
try
{
var hasGeolocation = typeof(navigator.geolocation)!=u;
if( !hasGeolocation ){
if( !pub.confirmation() ){
return false;
}
}
if ( ( typeof(geoPositionSimulator)!=u ) && (geoPositionSimulator.length > 0 ) ){
provider=geoPositionSimulator;
} else if (typeof(bondi)!=u && typeof(bondi.geolocation)!=u ) {
provider=bondi.geolocation;
} else if ( hasGeolocation ) {
provider=navigator.geolocation;
pub.getCurrentPosition = function(success, error, opts)
{
function _success(p) {
//for mozilla geode,it returns the coordinates slightly differently
var params;
if(typeof(p.latitude)!=u) {
params = {
timestamp: p.timestamp,
coords: {
latitude: p.latitude,
longitude: p.longitude
}
};
} else {
params = p;
}
success( params );
}
provider.getCurrentPosition(_success,error,opts);
}
} else if(typeof(window.blackberry)!=u && blackberry.location.GPSSupported) {
// set to autonomous mode
if(typeof(blackberry.location.setAidMode)==u) {
return false;
}
blackberry.location.setAidMode(2);
//override default method implementation
pub.getCurrentPosition = function(success,error,opts)
{
//passing over callbacks as parameter didn't work consistently
//in the onLocationUpdate method, thats why they have to be set outside
bb.success = success;
bb.error = error;
//function needs to be a string according to
//http://www.tonybunce.com/2008/05/08/Blackberry-Browser-Amp-GPS.aspx
if(opts['timeout']) {
bb.blackberryTimeoutId = setTimeout("handleBlackBerryLocationTimeout()",opts['timeout']);
} else {
//default timeout when none is given to prevent a hanging script
bb.blackberryTimeoutId = setTimeout("handleBlackBerryLocationTimeout()",60000);
}
blackberry.location.onLocationUpdate("handleBlackBerryLocation()");
blackberry.location.refreshLocation();
}
provider = blackberry.location;
} else if ( typeof(Mojo) !=u && typeof(Mojo.Service.Request)!="Mojo.Service.Request") {
provider = true;
pub.getCurrentPosition = function(success, error, opts)
{
parameters = {};
if( opts ) {
//http://developer.palm.com/index.php?option=com_content&view=article&id=1673#GPS-getCurrentPosition
if (opts.enableHighAccuracy && opts.enableHighAccuracy == true ){
parameters.accuracy = 1;
}
if ( opts.maximumAge ) {
parameters.maximumAge = opts.maximumAge;
}
if (opts.responseTime) {
if( opts.responseTime < 5 ) {
parameters.responseTime = 1;
} else if ( opts.responseTime < 20 ) {
parameters.responseTime = 2;
} else {
parameters.timeout = 3;
}
}
}
r = new Mojo.Service.Request( 'palm://com.palm.location' , {
method:"getCurrentPosition",
parameters:parameters,
onSuccess: function( p ){
success( { timestamp: p.timestamp,
coords: {
latitude: p.latitude,
longitude: p.longitude,
heading: p.heading
}
});
},
onFailure: function( e ){
if (e.errorCode==1) {
error({ code: 3,
message: "Timeout"
});
} else if (e.errorCode==2){
error({ code: 2,
message: "Position unavailable"
});
} else {
error({ code: 0,
message: "Unknown Error: webOS-code" + errorCode
});
}
}
});
}
}
else if (typeof(device)!=u && typeof(device.getServiceObject)!=u) {
provider=device.getServiceObject("Service.Location", "ILocation");
//override default method implementation
pub.getCurrentPosition = function(success, error, opts){
function callback(transId, eventCode, result) {
if (eventCode == 4) {
error({message:"Position unavailable", code:2});
} else {
//no timestamp of location given?
success( { timestamp:null,
coords: {
latitude: result.ReturnValue.Latitude,
longitude: result.ReturnValue.Longitude,
altitude: result.ReturnValue.Altitude,
heading: result.ReturnValue.Heading }
});
}
}
//location criteria
var criteria = new Object();
criteria.LocationInformationClass = "BasicLocationInformation";
//make the call
provider.ILocation.GetLocation(criteria,callback);
}
} else {
pub.getCurrentPosition = function(success, error, opts) {
pub.jsonp.fetch(ipGeolocationSrv,
function( p ){ success( { timestamp: p.timestamp,
coords: {
latitude: p.latitude,
longitude: p.longitude,
heading: p.heading
}
});});
}
provider = true;
}
}
catch (e){
if( typeof(console) != u ) console.log(e);
return false;
}
return provider!=null;
}
return pub;
}();
In Internet explorer works correctly for me, but when I try it on Google Chrome it shows me the location of another city near my region. I'd like to be able to solve it, and let me show my correct location in google chrome.
I noticed that in internet explorer it takes a few seconds more to load to visualize the location, perhaps in the google chrome lacks some pre-load cleaning or some compatibility.
In Internet Explorer it is right:
but in google chrome the location shows me wrong:
My objective is to be able to obtain my location with the map in an exact way in different browsers with javascript or some type code on the client side.
If anyone knows, of course, I appreciate your attention.

Google maps API V3 method fitBounds() using Prototypejs

I have a div as follows to display a google map:
#map {
width: 300px;
height: 300px;
border: 1px solid #DDD;
}
<div id="map"></div>
I want to display the map with a zoom level that fits the bounds of the above viewport.
When I code as follows it works fine:
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map($('#map')[0], {zoom: 10});
geocoder.geocode({ 'address': generatedAddress }, function (results, status) {
if (status == 'OK') {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
if (results[0].geometry.viewport)
map.fitBounds(results[0].geometry.viewport);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
When I use typeahead-addresspicker.js to generate the map it zooms in too far?
I've narrowed it down to the following code. When you call the AddressPicker.prototype.updateMap function the boundsForLocation option on AddressPicker.prototype.initMap function should return this.map.fitBounds(response.geometry.viewport); When I debug I can see that it is hitting the following code inside the AddressPicker.prototype.updateBoundsForPlace function as expected:
if (response.geometry.viewport) {
console.log('test');
return this.map.fitBounds(response.geometry.viewport);
}
What I don't understand is how it gets wired back to the google.maps.Map - I'm not familiar with ptototypejs? So basically running through it, we initilize the map by calling initMap, then we call the updateMap function. Inside updateMap function we are calling the following snippet of code:
if (_this.map) {
if ((_ref = _this.mapOptions) != null) {
_ref.boundsForLocation(response);
}
}
which is suppose to set the bounds by calling the updateBoundsForPlace but the google maps options doesnt expose any property called boundsForLocation?
AddressPicker.prototype.initMap = function() {
var markerOptions, _ref, _ref1;
if ((_ref = this.options) != null ? (_ref1 = _ref.map) != null ? _ref1.gmap : void 0 : void 0) {
this.map = this.options.map.gmap;
} else {
this.mapOptions = $.extend({
zoom: 3,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP,
boundsForLocation: this.updateBoundsForPlace
}, this.options.map);
this.map = new google.maps.Map($(this.mapOptions.id)[0], this.mapOptions);
}
this.lastResult = null;
markerOptions = $.extend({
draggable: true,
visible: false,
position: this.map.getCenter(),
map: this.map
}, this.options.marker || {});
this.marker = new google.maps.Marker(markerOptions);
if (markerOptions.draggable) {
return google.maps.event.addListener(this.marker, 'dragend', this.markerDragged);
}
};
AddressPicker.prototype.updateMap = function(event, place) {
if (this.options.placeDetails) {
return this.placeService.getDetails(place, (function(_this) {
return function(response) {
var _ref;
_this.lastResult = new AddressPickerResult(response);
if (_this.marker) {
_this.marker.setPosition(response.geometry.location);
_this.marker.setVisible(true);
}
if (_this.map) {
if ((_ref = _this.mapOptions) != null) {
_ref.boundsForLocation(response);
}
}
return $(_this).trigger('addresspicker:selected', _this.lastResult);
};
})(this));
} else {
return $(this).trigger('addresspicker:selected', place);
}
};
AddressPicker.prototype.updateBoundsForPlace = function(response) {
if (response.geometry.viewport) {
return this.map.fitBounds(response.geometry.viewport);
} else {
this.map.setCenter(response.geometry.location);
return this.map.setZoom(this.options.zoomForLocation);
}
};
Managed to fix by commenting out the following lines:
//if (response.geometry.viewport) {
// return this.map.fitBounds(response.geometry.viewport);
//} else {
this.map.setCenter(response.geometry.location);
return this.map.setZoom(this.options.zoomForLocation);
//}

Removing selected geojson feature with Google Maps JavaScript API

I'm using the Google Maps Javascript API to let users draw custom polygons with properties to be entered into a database. Before inserting them into the database though, they need to be able to delete selected shapes they've drawn.
This function isn't throwing any errors but it also isn't deleting the feature. What am I doing wrong?
var selectedshape;
function initMap() {
map = new google.maps.Map(document.getElementById('map2'), {
zoom: 1,
center: { lat: -1, lng: 1 }
});
function clearSelection() {
if (selectedShape) {
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
selectedShape = shape;
}
map.data.addListener('click', function(event) {
map.controls[google.maps.ControlPosition.TOP_RIGHT].clear()
setSelection(event.feature);
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(centerControlDiv);
map.data.revertStyle();
map.data.overrideStyle(event.feature, { strokeWeight: 8 });
selectID = event.feature.getProperty('uniqid')
selectID = event.feature.getProperty('uniqgeom')
$(".getSelectID").attr("id", selectID)
});
bounds = new google.maps.LatLngBounds();
map.data.addListener('addfeature', function(event) {
processPoints(event.feature.getGeometry(), bounds.extend, bounds);
map.setCenter(bounds.getCenter());
map.fitBounds(bounds);
var uniqid = "_" + Date.now();
feature_type = event.feature.getGeometry().getType()
if (feature_type == 'LineString') {
encoded_geom = event.feature.getProperty('uniqgeom') || google.maps.geometry.encoding.encodePath(event.feature.getGeometry().getArray());
} else {
encoded_geom = event.feature.getProperty('uniqgeom') || google.maps.geometry.encoding.encodePath(event.feature.getGeometry().getArray()[0].getArray())
}
event.feature.setProperty('encoded_geom', encoded_geom);
selectID = encoded_geom
$(".getSelectID").attr("id", selectID)
event.feature.setProperty('uniqid', uniqid);
});
function deleteSelectedShape() {
map.controls[google.maps.ControlPosition.TOP_RIGHT].clear()
if (selectedShape) {
map.data.forEach(function(feature) {
if (feature.getProperty('uniqid') == selectedShape.uniqid) {
map.data.remove(feature);
}
});
}
}
I believe the problem is a syntax error in
if (feature.getProperty('uniqid') == selectedShape.uniqid) {

Google Maps Cluster Dropdown?

I'm using Google maps to place pins on the world, and I'm using markercluster.js to cluster the pins when they get too close. What I'm looking to do is make it so you can hover over a cluster of pins and a drop down will appear showing the titles of the pins in that area.
I haven't seen anything on the forums about this, so I thought maybe someone else might have run into this and found a solution already. Thanks for any help in advance!
My code is just the typical way to add pins to the Google maps API. But I'll list it here just in case.
var bounds = new google.maps.LatLngBounds();
var markers = [];
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
//icon: '/bin/images/people/' + locations[i][4] + '-1.jpg'
});
markers.push(marker);
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker)
}
})(marker, i))
}
var clusterStyles = [{
textColor: 'white',
url: 'http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m1.png',
height: 50,
width: 50
}, {
textColor: 'white',
url: 'http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m1.png',
height: 50,
width: 50
}, {
textColor: 'white',
url: 'http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m1.png',
height: 50,
width: 50
}];
var mcOptions = {
gridSize: 50,
styles: clusterStyles,
maxZoom: 15
};
var markerCluster = new MarkerClusterer(map, markers, mcOptions);
map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function() {
map.setZoom(3);
google.maps.event.removeListener(listener)
});
You could consider the following approach.
Modify ClusterIcon by introducing clustermouseover event that will be triggered on mouseover event:
//Note: the remaining code is omitted from this function
ClusterIcon.prototype.onAdd = function() {
this.div_ = document.createElement('DIV');
var panes = this.getPanes();
panes.overlayMouseTarget.appendChild(this.div_);
var that = this;
google.maps.event.addDomListener(this.div_, 'mouseover', function() {
that.triggerClusterMouseOver();
});
};
where
ClusterIcon.prototype.triggerClusterMouseOver = function () {
var markerClusterer = this.cluster_.getMarkerClusterer();
google.maps.event.trigger(markerClusterer, 'clustermouseover', this.cluster_);
};
Attach event handler for displaying the corresponding information. The following example demonstrates how to display the list of names:
google.maps.event.addListener(markerClusterer, 'clustermouseover', function(clusterer) {
var markers = clusterer.getMarkers();
markers.forEach(function(marker){
infowindow.content += '<div>' + marker.title + '</div>';
});
infowindow.setPosition(clusterer.getCenter());
infowindow.open(clusterer.getMap());
});
Example: Plunker
You could consider the following approach Also its work for me :
public void initilizeMap() {
googleMap = mFragment.getMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
googleMap.getUiSettings().setZoomControlsEnabled(true`enter code here`); // true to`enter code here`
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
if (googleMap == null) {
Toast.makeText(getActivity(), "Sorry! unable to create maps",
Toast.LENGTH_SHORT).show();
}
mClusterManager = new ClusterManager<MyItem>(getActivity(), googleMap );
// googleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
googleMap.setOnMapLoadedCallback(this);
googleMap.setMyLocationEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.getUiSettings().setTiltGesturesEnabled(true);
MyItem offsetItem = new MyItem(Double.parseDouble(outletList.get(i).getMap_latitude()),
Double.parseDouble(outletList.get(i).getMap_longitude()), title , address);
mClusterManager.addItem(offsetItem);
googleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(offsetItem));
}
private class CustomInfoWindowAdapter implements InfoWindowAdapter {
Marker marker;
private View view;
private MyItem items;
public CustomInfoWindowAdapter(MyItem item) {
view = getActivity().getLayoutInflater().inflate(
R.layout.custom_info_window, null);
this.items = item;
}
#Override
public View getInfoContents(Marker marker) {
if (marker != null && marker.isInfoWindowShown()) {
marker.hideInfoWindow();
marker.showInfoWindow();
}
return null;
}
#Override
public View getInfoWindow(final Marker marker) {
this.marker = marker;
String url = null;
if (marker.getId() != null && markers != null && markers.size() > 0) {
if (markers.get(marker.getId()) != null
&& markers.get(marker.getId()) != null) {
url = markers.get(marker.getId());
}
}
final ImageView image = ((ImageView) view.findViewById(R.id.badge));
if (url != null && !url.equalsIgnoreCase("null")
&& !url.equalsIgnoreCase("")) {
imageLoader.displayImage(url, image, options,
new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
super.onLoadingComplete(imageUri, view,
loadedImage);
getInfoContents(marker);
}
});
} else {
image.setImageResource(R.drawable.ic_launcher);
}
final String title = items.getTitle();
Log.e(TAG, "TITLE : "+title);
final TextView titleUi = ((TextView) view.findViewById(R.id.title));
if (title != null) {
titleUi.setText(title);
} else {
titleUi.setText("");
}
final String address = items.getAddress();
final TextView snippetUi = ((TextView) view
.findViewById(R.id.snippet));
if (address != null) {
snippetUi.setText(address);
} else {
snippetUi.setText("");
}

How to set the zoom level for a single location on a bing map

I have the following js object:
virtualEarthBingMap = {
map : "",
propertiesDataArray : [],
locations : [],
initialLatLong : "",
initialZoom : "",
isInitialized : false,
MM : "",
overMap : false,
init : function(){
},
addLoadEvent : function(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
},
pushpinObj : function(){
this.number;
this.lat;
this.longitude;
this.type;
this.iconstyle;
},
generatePushpinData : function(rowCount){
if(rowCount == undefined){
rowCount = "";
}
//initiate hidden field objects
var pushPinNumberObj = document.getElementsByName("pushpin-number"+rowCount);
var pushPinLatObj = document.getElementsByName("pushpin-lat"+rowCount);
var pushPinLongObj = document.getElementsByName("pushpin-long"+rowCount);
var pushPinTypeObj = document.getElementsByName("pushpin-type"+rowCount);
var pushPinIconStyleObj = document.getElementsByName("pushpin-iconstyle"+rowCount);
for(i=0; i < pushPinNumberObj.length; i++){
var propertyData = new virtualEarthBingMap.pushpinObj;
propertyData.number = Number(pushPinNumberObj[i].value);
propertyData.lat = pushPinLatObj[i].value;
propertyData.longitude = pushPinLongObj[i].value;
propertyData.type = pushPinTypeObj[i].value;
if(pushPinIconStyleObj!= null && pushPinIconStyleObj.length>0){
propertyData.iconstyle = pushPinIconStyleObj[i].value;
}
virtualEarthBingMap.propertiesDataArray.push(propertyData);
}
},
mouseEvent: function (e){
if(e.eventName == 'mouseout')
virtualEarthBingMap.overMap = false;
else if(e.eventName == 'mouseover')
virtualEarthBingMap.overMap = true;
},
//renders VEMap to myMap div
getMap: function (mapObj, rowCount) {
if(rowCount == undefined){
rowCount = "";
}
try{
virtualEarthBingMap.MM = Microsoft.Maps;
//Set the map options
var mapOptions = { credentials:document.getElementById("bingKey"+rowCount).value,
mapTypeId: virtualEarthBingMap.MM.MapTypeId.road,
enableClickableLogo: false,
enableSearchLogo: false,
tileBuffer: Number(document.getElementById("tileBuffer"+rowCount).value)};
virtualEarthBingMap.map = new virtualEarthBingMap.MM.Map(document.getElementById("map"+rowCount), mapOptions);
var dataLayer = new virtualEarthBingMap.MM.EntityCollection();
virtualEarthBingMap.map.entities.push(dataLayer);
var pushpinOptions,pushpin,propertyData;
for(var x=0; x < virtualEarthBingMap.propertiesDataArray.length; x++){
propertyData = virtualEarthBingMap.propertiesDataArray[x];
if(document.getElementsByName(("pushpin-iconstyle"+rowCount)).length > 0)//All other maps push pins
{
pushpinOptions ={icon: mapObj.getCustomIcon(propertyData.iconstyle)};
}
else//classic search map push pin
{
pushpinOptions ={icon: mapObj.getCustomIcon(propertyData.type)};
}
// creating a pushpin for every property
pushpin = new virtualEarthBingMap.MM.Pushpin(new virtualEarthBingMap.MM.Location(Number(propertyData.lat), Number(propertyData.longitude)), pushpinOptions);
pushpin.setOptions({typeName:("pushpin"+rowCount)});
// set pushpin on map
dataLayer.push(pushpin);
// adding to locations array to be used for setMapView when there are more than one property on a map
virtualEarthBingMap.locations.push(new virtualEarthBingMap.MM.Location(Number(propertyData.lat), Number(propertyData.longitude)));
};
//Handle blur event for map
if(rowCount == ""){
$("html").click(function() {
if(!virtualEarthBingMap.overMap)
virtualEarthBingMap.map.blur();
});
}
//Set the events for map, pushpin and infobox
virtualEarthBingMap.map.blur();//Removes focus from the map control
virtualEarthBingMap.MM.Events.addHandler(pushpin, 'mouseover', function (e) { virtualEarthBingMap.displayInfobox(e, rowCount)});
virtualEarthBingMap.MM.Events.addHandler(pushpin, 'click', function (e) { virtualEarthBingMap.displayInfobox(e, rowCount)});
virtualEarthBingMap.MM.Events.addHandler(virtualEarthBingMap.map, 'viewchangeend', virtualEarthBingMap.hideInfobox);
virtualEarthBingMap.MM.Events.addHandler(virtualEarthBingMap.map, 'mouseout', virtualEarthBingMap.mouseEvent);
virtualEarthBingMap.MM.Events.addHandler(virtualEarthBingMap.map, 'mouseover', virtualEarthBingMap.mouseEvent);
//Plot the pushpin
mapObj.setMapView();
}catch(e){
mapObj.displayMapError(rowCount);
}
//clean up properties data array
virtualEarthBingMap.propertiesDataArray = [];
},
//returns flyout info id
getFlyoutId : function(lat, longitude, rowCount){
if(rowCount == undefined){
rowCount = "";
}
try{
var flyoutId = "flyout"+rowCount+"[" + lat + "][" + longitude + "]";
return flyoutId
}catch(e){}
},
//Show info box
displayInfobox: function (e, rowCount) {
var disableToolTip = $('#disableToolTip').val();
if ((disableToolTip == undefined || disableToolTip == "" || disableToolTip == 'false') && e.targetType == 'pushpin') {
virtualEarthBingMap.hideInfobox();
if(rowCount == undefined){
rowCount = "";
}
var flyoutLat = $("input[name='pushpin-lat"+rowCount+"'][type='hidden']").val();
var flyoutLong = $("input[name='pushpin-long"+rowCount+"'][type='hidden']").val();
var flyoutId = virtualEarthBingMap.getFlyoutId(flyoutLat,flyoutLong, rowCount);
var infobox = document.getElementById(flyoutId);
$(infobox).css("display","inline");
$(infobox).css("z-index","10000");
$(infobox).css("position","absolute");
var pushpinPosition;
if(rowCount != "")
{
pushpinPosition = $('.pushpin'+rowCount).offset();
$(infobox).css("top",pushpinPosition.top + "px");
$(infobox).css("left",pushpinPosition.left + "px");
} else {
//original position
pushpinPosition = virtualEarthBingMap.map.tryLocationToPixel(e.target.getLocation(), virtualEarthBingMap.MM.PixelReference.page);
$(infobox).css("top",(pushpinPosition.y-40) + "px");
$(infobox).css("left",(pushpinPosition.x-5) + "px");
}
$('body').append(infobox);
setTimeout(virtualEarthBingMap.hideInfobox,12000); //hide infobox after 12 sec
}
},
//Hide infobox
hideInfobox: function () {
$('.display-off').css("display","none");
}
}//End virtualEarthBingMap
I am trying to set the bing map to zoom in on a location right now I am using this script to differentiate between single and multiple locations:
setMapView: function () {
if (virtualEarthBingMap.locations.length > 1) {
// set mapview for multiple hotels that dynamically sets the zoom so all pushpins are shown in ititial map window
virtualEarthBingMap.map.setView({bounds:virtualEarthBingMap.MM.LocationRect.fromLocations(virtualEarthBingMap.locations),padding:10});
} else {
// set mapview for single hotel
virtualEarthBingMap.map.setView({center:new Microsoft.Maps.Location(virtualEarthBingMap.propertiesDataArray[0].lat,virtualEarthBingMap.propertiesDataArray[0].longitude),zoom:15});
}
}
This is working on multiple locations but not on single locations. Anyone have any ideas?
A padding of 10 won't have an effect on the zoom level unless the map is less than 20 pixels wide. A simple solution is to set the zoom level instead. I recommend zoom level 15 or 16 for a single location.

Categories

Resources