how to get google map js api get lat, lng with selected address

This code provides an address autocomplete feature using the Google Places API. When a user types in the “from” field, it shows address suggestions. Upon selecting an address, it needs to retrieves and displays the latitude and longitude of the selected address, which can be used to fetch related addresses for the “to” field. The script initializes the autocomplete functionality, handles input events, fetches and displays suggestions, and processes the selected place details.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> <!DOCTYPE html>
<html>
<head>
<title>Place Autocomplete Address Form</title>
<link href="https://fonts.googleapis.com/css?family=Roboto:400,500" rel="stylesheet" />
</head>
<body>
<div class="searchDiv">
<form id="addressForm" action="getAddress.php" method="post">
<div class="fromDiv">
<input id="from" name="fromAddress" type="text" placeholder="Search from address" />
<input type="text" name="s_latitude" id="s_latitude" value="" />
<input type="text" name="s_longitude" id="s_longitude" value="" />
<div id="fromTitle"></div>
<ul id="selectedFrom"></ul>
</div>
<div class="toDiv">
<input id="to" name="toAddress" type="text" placeholder="Search to address" />
<div id="toTitle"></div>
<ul id="selectedTo"></ul>
</div>
<button class="submit" type="submit">Submit</button>
</form>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=key&callback=init&libraries=places&v=weekly" defer></script>
<script>
let fromInput;
let toInput;
let token;
let fromRequest = {
input: "",
language: "en-US",
region: "uk",
sessionToken: null
};
let toRequest = {
input: "",
language: "en-US",
region: "uk",
sessionToken: null
};
async function init() {
token = new google.maps.places.AutocompleteSessionToken();
fromInput = document.getElementById("from");
toInput = document.getElementById("to");
fromInput.addEventListener("input", () => makeAcRequest(fromInput, fromRequest, document.getElementById("fromTitle"), document.getElementById("selectedFrom")));
toInput.addEventListener("input", () => makeAcRequest(toInput, toRequest, document.getElementById("toTitle"), document.getElementById("selectedTo")));
fromRequest = refreshToken(fromRequest);
toRequest = refreshToken(toRequest);
}
async function makeAcRequest(input, request, titleElement, resultsElement) {
// Reset elements and exit if an empty string is received.
if (input.value == "") {
titleElement.innerText = "";
resultsElement.replaceChildren();
return;
}
// Add the latest char sequence to the request.
request.input = input.value;
// Fetch autocomplete suggestions and show them in a list.
try {
const {
suggestions
} = await google.maps.places.AutocompleteSuggestion.fetchAutocompleteSuggestions(request);
titleElement.innerText = `Query predictions for "${request.input}"`;
// Clear the list first.
resultsElement.replaceChildren();
for (const suggestion of suggestions) {
const placePrediction = suggestion.placePrediction;
// Create a link for the place, add an event handler to fetch the place.
const a = document.createElement("a");
a.addEventListener("click", () => {
onPlaceSelected(placePrediction.toPlace(), input, resultsElement, titleElement);
});
a.innerText = placePrediction.text.toString();
// Create a new list element.
const li = document.createElement("li");
li.appendChild(a);
resultsElement.appendChild(li);
}
} catch (error) {
console.error('Error fetching autocomplete suggestions:', error);
}
}
// Event handler for clicking on a suggested place.
async function onPlaceSelected(place, input, resultsElement, titleElement) {
try {
await place.fetchFields({
fields: ["formattedAddress"],
});
// Set the input value to the selected address
input.value = place.formattedAddress || '';
// Clear other elements
resultsElement.replaceChildren();
titleElement.innerText = "Selected Place:";
// Optionally, you can reset the autocomplete request here
fromRequest = refreshToken(fromRequest);
toRequest = refreshToken(toRequest);
} catch (error) {
console.error('Error fetching place details:', error);
}
}
// Helper function to refresh the session token.
async function refreshToken(request) {
// Create a new session token and add it to the request.
request.sessionToken = new google.maps.places.AutocompleteSessionToken();
return request;
}
window.init = init;
</script>
</body>
</html>```
</code>
<code> <!DOCTYPE html> <html> <head> <title>Place Autocomplete Address Form</title> <link href="https://fonts.googleapis.com/css?family=Roboto:400,500" rel="stylesheet" /> </head> <body> <div class="searchDiv"> <form id="addressForm" action="getAddress.php" method="post"> <div class="fromDiv"> <input id="from" name="fromAddress" type="text" placeholder="Search from address" /> <input type="text" name="s_latitude" id="s_latitude" value="" /> <input type="text" name="s_longitude" id="s_longitude" value="" /> <div id="fromTitle"></div> <ul id="selectedFrom"></ul> </div> <div class="toDiv"> <input id="to" name="toAddress" type="text" placeholder="Search to address" /> <div id="toTitle"></div> <ul id="selectedTo"></ul> </div> <button class="submit" type="submit">Submit</button> </form> </div> <script src="https://maps.googleapis.com/maps/api/js?key=key&callback=init&libraries=places&v=weekly" defer></script> <script> let fromInput; let toInput; let token; let fromRequest = { input: "", language: "en-US", region: "uk", sessionToken: null }; let toRequest = { input: "", language: "en-US", region: "uk", sessionToken: null }; async function init() { token = new google.maps.places.AutocompleteSessionToken(); fromInput = document.getElementById("from"); toInput = document.getElementById("to"); fromInput.addEventListener("input", () => makeAcRequest(fromInput, fromRequest, document.getElementById("fromTitle"), document.getElementById("selectedFrom"))); toInput.addEventListener("input", () => makeAcRequest(toInput, toRequest, document.getElementById("toTitle"), document.getElementById("selectedTo"))); fromRequest = refreshToken(fromRequest); toRequest = refreshToken(toRequest); } async function makeAcRequest(input, request, titleElement, resultsElement) { // Reset elements and exit if an empty string is received. if (input.value == "") { titleElement.innerText = ""; resultsElement.replaceChildren(); return; } // Add the latest char sequence to the request. request.input = input.value; // Fetch autocomplete suggestions and show them in a list. try { const { suggestions } = await google.maps.places.AutocompleteSuggestion.fetchAutocompleteSuggestions(request); titleElement.innerText = `Query predictions for "${request.input}"`; // Clear the list first. resultsElement.replaceChildren(); for (const suggestion of suggestions) { const placePrediction = suggestion.placePrediction; // Create a link for the place, add an event handler to fetch the place. const a = document.createElement("a"); a.addEventListener("click", () => { onPlaceSelected(placePrediction.toPlace(), input, resultsElement, titleElement); }); a.innerText = placePrediction.text.toString(); // Create a new list element. const li = document.createElement("li"); li.appendChild(a); resultsElement.appendChild(li); } } catch (error) { console.error('Error fetching autocomplete suggestions:', error); } } // Event handler for clicking on a suggested place. async function onPlaceSelected(place, input, resultsElement, titleElement) { try { await place.fetchFields({ fields: ["formattedAddress"], }); // Set the input value to the selected address input.value = place.formattedAddress || ''; // Clear other elements resultsElement.replaceChildren(); titleElement.innerText = "Selected Place:"; // Optionally, you can reset the autocomplete request here fromRequest = refreshToken(fromRequest); toRequest = refreshToken(toRequest); } catch (error) { console.error('Error fetching place details:', error); } } // Helper function to refresh the session token. async function refreshToken(request) { // Create a new session token and add it to the request. request.sessionToken = new google.maps.places.AutocompleteSessionToken(); return request; } window.init = init; </script> </body> </html>``` </code>
   <!DOCTYPE html>
   <html>

   <head>
    <title>Place Autocomplete Address Form</title>
    <link href="https://fonts.googleapis.com/css?family=Roboto:400,500" rel="stylesheet" />
    
   </head>

    <body>
    <div class="searchDiv">
        <form id="addressForm" action="getAddress.php" method="post">
            <div class="fromDiv">
                <input id="from" name="fromAddress" type="text" placeholder="Search from address"       />
                <input type="text" name="s_latitude" id="s_latitude" value="" />
                <input type="text" name="s_longitude" id="s_longitude" value="" />
                <div id="fromTitle"></div>
                <ul id="selectedFrom"></ul>
            </div>
            <div class="toDiv">
                <input id="to" name="toAddress" type="text" placeholder="Search to address" />
                <div id="toTitle"></div>
                <ul id="selectedTo"></ul>
            </div>
            <button class="submit" type="submit">Submit</button>
        </form>
    </div>

    <script src="https://maps.googleapis.com/maps/api/js?key=key&callback=init&libraries=places&v=weekly" defer></script>
    <script>
        let fromInput;
        let toInput;
        let token;

        let fromRequest = {
            input: "",
            language: "en-US",
            region: "uk",
            sessionToken: null
        };

        let toRequest = {
            input: "",
            language: "en-US",
            region: "uk",
            sessionToken: null
        };

        async function init() {

            token = new google.maps.places.AutocompleteSessionToken();
            fromInput = document.getElementById("from");
            toInput = document.getElementById("to");

            fromInput.addEventListener("input", () => makeAcRequest(fromInput, fromRequest, document.getElementById("fromTitle"), document.getElementById("selectedFrom")));
            toInput.addEventListener("input", () => makeAcRequest(toInput, toRequest, document.getElementById("toTitle"), document.getElementById("selectedTo")));

            fromRequest = refreshToken(fromRequest);
            toRequest = refreshToken(toRequest);
        }

        async function makeAcRequest(input, request, titleElement, resultsElement) {
            // Reset elements and exit if an empty string is received.
            if (input.value == "") {
                titleElement.innerText = "";
                resultsElement.replaceChildren();
                return;
            }

            // Add the latest char sequence to the request.
            request.input = input.value;

            // Fetch autocomplete suggestions and show them in a list.
            try {
                const {
                    suggestions
                } = await google.maps.places.AutocompleteSuggestion.fetchAutocompleteSuggestions(request);

                titleElement.innerText = `Query predictions for "${request.input}"`;
                // Clear the list first.
                resultsElement.replaceChildren();

                for (const suggestion of suggestions) {
                    const placePrediction = suggestion.placePrediction;
                    // Create a link for the place, add an event handler to fetch the place.
                    const a = document.createElement("a");

                    a.addEventListener("click", () => {
                        onPlaceSelected(placePrediction.toPlace(), input, resultsElement, titleElement);
                    });
                    a.innerText = placePrediction.text.toString();

                    // Create a new list element.
                    const li = document.createElement("li");

                    li.appendChild(a);
                    resultsElement.appendChild(li);
                }
            } catch (error) {
                console.error('Error fetching autocomplete suggestions:', error);
            }
        }

        // Event handler for clicking on a suggested place.
        async function onPlaceSelected(place, input, resultsElement, titleElement) {
            try {
                await place.fetchFields({
                    fields: ["formattedAddress"],
                });

                // Set the input value to the selected address
                input.value = place.formattedAddress || '';

                // Clear other elements
                resultsElement.replaceChildren();
                titleElement.innerText = "Selected Place:";

                // Optionally, you can reset the autocomplete request here
                fromRequest = refreshToken(fromRequest);
                toRequest = refreshToken(toRequest);

            } catch (error) {
                console.error('Error fetching place details:', error);
            }
        }

        // Helper function to refresh the session token.
        async function refreshToken(request) {
            // Create a new session token and add it to the request.
            request.sessionToken = new google.maps.places.AutocompleteSessionToken();
            return request;
        }

        window.init = init;
    </script>
    </body>

   </html>```

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật