Ionic 2组件中Google Maps标记信息框无法显示商家名称问题
Hi there! Let's break down why you can't access this.vendor.shop_name in your addMarker function, and walk through the most likely fixes based on your scenario:
1. The this Context Is Probably Wrong
In JavaScript, this changes depending on how a function is called. If addMarker is triggered as a Google Maps callback (like on map load) or an event handler, this might not point to your component instance anymore—it could be pointing to the Google Maps object or the global window instead.
Fixes:
- Use an arrow function for
addMarker: Arrow functions inherit thethisfrom their surrounding scope, so your component'sthiswill stay intact.addMarker = () => { const content = `<div>${this.vendor.shop_name}</div>`; // Rest of your marker creation code } - Or save a reference to
thisbeforehand:initMap() { const componentInstance = this; // Save the component's this function addMarker() { const content = `<div>${componentInstance.vendor.shop_name}</div>`; // Rest of your marker code } addMarker(); }
2. Your Vendor Data Might Not Be Loaded Yet
You're fetching vendors via the WooCommerce API, which is an asynchronous operation. If you call addMarker before the API request finishes, this.vendor will still be empty or undefined—so shop_name won't exist.
Fix:
Wait for the API response to complete before calling addMarker. Use async/await or .then() to ensure your data is ready first:
async loadVendorsAndMarkers() { try { const apiResponse = await fetch('your-woocommerce-api-endpoint'); this.vendor = await apiResponse.json(); // Assuming this returns a single vendor this.addMarker(); // Now call addMarker once data is loaded } catch (error) { console.error('Failed to load vendors:', error); } }
3. Double-Check Your Data Structure
It's easy to mix up object keys or forget that your vendor data might be an array (not a single object). For example:
- If your API returns a list of vendors (an array), you need to loop through them instead of accessing
this.vendor.shop_namedirectly. - Make sure the key name matches exactly what the API returns—maybe it's
shopNameinstead ofshop_name?
Quick Debug Step:
Add a console log inside addMarker to inspect what you're working with:
addMarker() { console.log('Current vendor data:', this.vendor); // See if this has the shop_name property console.log('Current this:', this); // Verify this points to your component }
4. Framework-Specific Binding Issues (If Using Vue/React)
If you're building this with a framework like Vue or React:
- Vue: Ensure
vendoris declared in your component'sdata()or usingref/reactive—otherwise it won't be reactive or accessible viathis. - React: Use
useStateoruseReducerto manage your vendor state, soaddMarkercan access the latest data when the component re-renders.
内容的提问来源于stack exchange,提问作者Lorenzo Varano

