使用存储验证手机号的Cookie标记Google Map Marker时出现undefined问题
Hey there! Let's sort out that marker label issue where you're getting PhoneNumber=undefined; +1########## instead of just the verified phone number. Here's what's going wrong and how to fix it:
What's Causing the Problem?
When you set the cookie with document.cookie = (firebase.auth().currentUser.phoneNumber);, you're not following the standard key=value format for cookies. This leads browsers to interpret the cookie incorrectly, and if there's an existing leftover cookie (like PhoneNumber=undefined from prior tests), document.cookie will return all cookies concatenated with semicolons—hence the messy mixed text in your marker label.
Step-by-Step Solution
1. Fix the Cookie Setup
First, store your phone number in a properly formatted cookie with a clear, unique key name (e.g., verifiedPhone). This avoids conflicts with other cookies and makes retrieval straightforward:
'signInSuccess': function(user, credential, redirectUrl) { const verifiedPhone = firebase.auth().currentUser.phoneNumber; // Encode the number to handle special characters like "+", add persistence settings document.cookie = `verifiedPhone=${encodeURIComponent(verifiedPhone)}; path=/; max-age=86400`; handleSignedInUser(user); return true; }
encodeURIComponent()ensures the phone number (including the+sign) is stored correctly without formatting issues.path=/makes the cookie accessible across your entire site.max-age=86400sets the cookie to expire after 24 hours (adjust this value to match your needs).
2. Retrieve the Cookie Properly
Instead of grabbing the entire document.cookie string (which includes all cookies stored by the browser), use a helper function to extract only the verifiedPhone value you need:
// Helper function to fetch a specific cookie by its key name function getCookie(cookieName) { const cookieString = `; ${document.cookie}`; const cookieParts = cookieString.split(`; ${cookieName}=`); if (cookieParts.length === 2) { return decodeURIComponent(cookieParts.pop().split(';').shift()); } return null; // Return null if the cookie doesn't exist } // Get the verified phone number and set the marker const markerLabel = getCookie('verifiedPhone'); const marker = new google.maps.Marker({ position: { lat: data.User.l[0], lng: data.User.l[1] }, map: map, label: markerLabel || 'No Number' // Optional fallback text if cookie is missing });
Why This Works
- Using a structured key-value cookie prevents mixing with other existing cookies.
- The helper function precisely extracts only your verified phone number, so your marker label will show just
+1##########without any extra, unwanted text.
Give this a try, and your marker labels should display cleanly with just the verified phone number!
内容的提问来源于stack exchange,提问作者BIlly BOB

