Created
September 5, 2023 07:21
-
-
Save wangziling/c62a3279ed42c139b469fc53084bd71a to your computer and use it in GitHub Desktop.
Get google AutoComplete element related suggestion element.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _ from 'lodash'; | |
// Optional. | |
import $ from 'jquery'; | |
// You need to mount/init the autoComplete utils first. | |
// const autocomplete = new google.maps.places.Autocomplete(inputElement, config); | |
function getPredictionEle (autocomplete: any): null | Element { | |
// Use this to make sure that we will not fall into an endless loop. | |
let MAX_DEEP_DIVE_IN_LEVEL = 50; | |
let foundEle = null as Element | null; | |
// @ts-ignore | |
_.some(autocomplete.gm_accessors_, function (v: any) { | |
// @ts-ignore | |
const loop = function (data: any) { | |
if (!(typeof data === 'object' && data)) { | |
return false; | |
} | |
MAX_DEEP_DIVE_IN_LEVEL--; | |
if (MAX_DEEP_DIVE_IN_LEVEL < 0) { | |
return true; | |
} | |
if (!(typeof data.formattedPrediction === 'object' && data.formattedPrediction)) { | |
if (typeof data.gm_bindings_ === 'object' && data.gm_bindings_) { | |
return loop(data.gm_bindings_); | |
} | |
return _.some(data, function (dataV) { | |
return loop(dataV); | |
}); | |
} | |
const loopPrediction = function (dataPrediction: any): boolean { | |
return _.some(dataPrediction, function (predictionItem: any, key: string) { | |
// No need to dive into these properties. | |
if (['gm_accessors_', 'gm_bindings_'].includes(key)) { | |
return false; | |
} | |
MAX_DEEP_DIVE_IN_LEVEL--; | |
if (MAX_DEEP_DIVE_IN_LEVEL < 0) { | |
return true; | |
} | |
if (!(predictionItem && typeof predictionItem === 'object')) { | |
return false; | |
} | |
if (predictionItem instanceof Element) { | |
// If you didn't want to use jQuery. | |
// if (predictionItem.classList.contains('pac-container')) { | |
if ($(predictionItem).hasClass('pac-container')) { | |
foundEle = predictionItem; | |
return true; | |
} | |
return false; | |
} | |
return loopPrediction(predictionItem); | |
}); | |
}; | |
return loopPrediction(data.formattedPrediction); | |
}; | |
return loop(v); | |
}); | |
// div.pac-container.pac-logo | |
return foundEle; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment