How to open a mobile device's map app when a user clicks on a link?

前端 未结 7 1928
南旧
南旧 2020-12-23 01:56

I have a web app where if a user clicks on a link it should open up a map. The best solution that I can think of is to open up a new tab/window to google maps using the

相关标签:
7条回答
  • 2020-12-23 02:52

    Here's my jQuery solution for this issue. I wanted to be able to detect the correct map to open up. In 2019, microformats still don't automatically make a link for mobile phones.

    I used the solution from this article https://medium.com/@colinlord/opening-native-map-apps-from-the-mobile-browser-afd66fbbb8a4 but modified it to make it current and dynamic.

    And, modified the code so I could have an address block in my html. That address is stripped to the basics and sent to the appropriate maps app.

    HTML

    <span class="map-link">6555 Hollywood Blvd<br/>Hollywood, CA 90028</span>
    

    JavaScript

    $(document).on('click','.map-link',function() {
        var address = $(this).html();
        address = $('<div/>')
          .html(address)
          .text() // strip tags
          .replace(/\s\s+/g, " "); // remove spaces
        address = encodeURIComponent(address);
        if ((navigator.platform.indexOf('iPhone') != -1) || (navigator.platform.indexOf('iPad') != -1) || (navigator.platform.indexOf('iPod') != -1)){/* if we're on iOS, open in Apple Maps */
            window.open('http://maps.apple.com/?q=' + address);
        } else { /* else use Google */
            window.open('https://maps.google.com/maps?q=' + address);
        }
    });
    

    CSS

    .map-link { text-decoration: underline; text-decoration-style: dotted;cursor: pointer ;}
    .map-link:hover { text-decoration-style:solid;}
    
    0 讨论(0)
提交回复
热议问题