13

Details

  • I want to print a map base on any address that are stored in my <span>
  • My address is : 410 walker street Lowell MA 01851
  • My <span> is Address: <span id="address" > 410 walker street Lowell MA 01851 </span>
  • I want to use Google Map API for that

What I have tried

Address: <span id="address" > 410 walker street Lowell MA 01851 </span>

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

<!-- "Highlight a place or an address" -->
<iframe 

width="600" height="450" frameborder="0" style="border:0"
src="

https://www.google.com/maps/embed/v1/place?q=

410+walker+street+Lowell+MA+01851

&key=*****

">

</iframe>

Here is my result

enter image description here

So far so good, everything is working, and it's work because I input the address manually like this ?q = 410+walker+street+Lowell+MA+01851

but I don't want the input the address manually. How do I do this dynamically ? I need some suggestions - please.

My Approach

  • I was wondering if I can store my address in a variable $address

  • $address = "410 walker street Lowell MA 01851";

  • and finally print them back out as "410+walker+street+Lowell+MA+01851" in part of my HTML attribute src="".

Questions

  • I am not sure at all that this approach is the best practice for this.
  • Is it possible ? How ?
  • Can anyone help shed the light on this ?
iori
  • 3,236
  • 12
  • 43
  • 78

6 Answers6

14

I was doing similar stuff.

If you find ?pb= within the iframe url, it means that it's cached somewhere. In case you put your own address, have in mind that it needs to be geolocated (lat, lng) and the iframe itself doesn't do that for you.

It is possible to do the work without API Key you could try to do something like:

$(document).ready( function(){
    var addr = 'Any Street 670, Any City';
    function(){  

        var embed= "<iframe width='425' height='350' frameborder='0'  
        scrolling='no' marginheight='0' marginwidth='0'    
        src='https://maps.google.com/maps?&amp;q="+   
        encodeURIComponent( addr ) +  
        "&amp;output=embed'></iframe>";  

        $('.place').html(embed);
    });
});

It is working nicely for me.

For working also with coordinates, have a look at this SO question.

Zyo
  • 1,934
  • 21
  • 25
Evhz
  • 8,852
  • 9
  • 51
  • 69
  • 1
    didn't quite work for me so I had to use the following: const googleSrc = 'https://maps.google.com/maps?q=' + encodeURIComponent(location) + '&t=&z=13&ie=UTF8&iwloc=&output=embed'; – 72GM Apr 27 '22 at 12:42
8

Use $.text() to retrieve the address, encode it(via encodeURIComponent), and then set the src-attribute of the iframe(by using the encoded address):

<span id="address"> 410 walker street Lowell MA 01851 </span>
<iframe id="map" width="600" height="450"></iframe>
<script  type="text/javascript">
jQuery(
  function($)
  {
       var q=encodeURIComponent($('#address').text());
       $('#map')
        .attr('src',
             'https://www.google.com/maps/embed/v1/place?key=***&q='+q);

  }
);
</script>

Demo: http://jsfiddle.net/doktormolle/pkjq1hrb/

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
  • I use your snipper with my API_KEY. It didn't work. I wonder what did you do to make it work on the JSFiddle. – iori Jan 10 '15 at 21:45
  • 1
    You must activate the **Google Maps Embed API** for the particular project inside the [Google developer console](https://console.developers.google.com/project) – Dr.Molle Jan 10 '15 at 22:04
  • 2
    It's not only the key, you must activate the API. When you already have been able to load a embedded map by using your key(e.g. on your own server), you probably have defined the referers for the key inside the developer -console. That's what I did to secure my key, I've set the following referer: `fiddle.jshell.net/doktormolle/*` (where **doktormolle** is my jsfiddle-account). You may do the same. – Dr.Molle Jan 10 '15 at 22:09
  • So if I register the API with my website, can I still test it localhost. – iori Jan 15 '15 at 01:28
  • I replaced my API key and your API key and it's doesn't work :( – iori Jan 15 '15 at 01:28
  • define "did not work", you should see a error-message when it didn't work. – Dr.Molle Jan 15 '15 at 01:35
  • 1
    Take a look at the developer-tools, there should be a request to `https://www.google.com/maps/embed....`, what's the response? When there isn't such an request something else is wrong(I can't tell you what without the exact code) – Dr.Molle Jan 15 '15 at 01:50
  • 1
    With the given key I get in Firefox ***The Google Maps API server rejected your request. This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console: Learn more: https://code.google.com/apis/console*** , which is related to my 2nd comment(the API is not enabled). When you share your key you should set the allowed referers, otherwise anybody may use your key. – Dr.Molle Jan 15 '15 at 01:55
  • I am back now. I finally set the referred as you suggested. I can see the error message now. The error said `The Google Maps API server rejected your request. Invalid request. Missing the 'q' parameter.` - but how's come, your is working. – iori Jan 15 '15 at 14:57
  • According to your link [http://jsfiddle.net/doktormolle/pkjq1hrb/](http://jsfiddle.net/doktormolle/pkjq1hrb/), I couldn't get my map to load - I did EXACT same thing as your except the key of course, that's why I asked for another similar question to this. – iori Jan 21 '15 at 21:44
  • Which part may be misunderstood in my comment: **You must activate the Google Maps Embed API for the particular project inside the Google developer console** .....sorry, this is not a programming-question, when you're not able to activate the API you can't use the API, no matter how often you ask the question. – Dr.Molle Jan 21 '15 at 21:56
  • I've already have the API key, I also already activate the API, see [here](https://dl.dropboxusercontent.com/u/56134944/qouta.JPG) – iori Jan 21 '15 at 21:58
  • Provide a(nother) demo, not an image. – Dr.Molle Jan 21 '15 at 22:07
7
<?php $address = 'Any Street 670, Any City' ; /* Insert address Here */

echo '<iframe width="100%" height="170" frameborder="0" src="https://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=' . str_replace(",", "", str_replace(" ", "+", $address)) . '&z=14&output=embed"></iframe>';
                            ?>
Arindam
  • 71
  • 2
  • 4
2

you wanna show location based on address that user input ? may be this will help you, but in limitation about data storing on google place server. try this code snippet, may be a little help for you.

I've edited my answer, because you're not using jquery. If you're using jquery, look at my previous revision..

var map_options = {
    center: new google.maps.LatLng(-2.548926, 118.0148634),
    zoom: 4,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};

var map = new google.maps.Map(document.getElementById("map_canvas"), map_options);

var input = document.getElementById("keyword");
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo("bounds", map);

var marker = new google.maps.Marker({
    map: map,
    zoom: 14,
    animation: google.maps.Animation.BOUNCE
});

google.maps.event.addListener(autocomplete, "place_changed", function () {
    var place = autocomplete.getPlace();

    if (place.geometry.viewport) {
        map.fitBounds(place.geometry.viewport);
    } else {
        map.setCenter(place.geometry.location);
        map.setZoom(15);
    }

    marker.setPosition(place.geometry.location);
});

google.maps.event.addListener(map, "click", function (event) {
    marker.setPosition(event.latLng);
});
<script src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<div id="map_canvas" style="width:530px; height:250px"></div>
<label for="keyword">Location :</label>
<input type="text" name="keyword" id="keyword">
Eko Junaidi Salam
  • 1,663
  • 1
  • 18
  • 26
0

Depending on what you want to accomplish, if the goal is to show the visitor the nearest location of a business to their current location, then it's possible to do this using a combination of IP intel (city network) and their GPS location, on mobile.

I'm not sure how you would do this yourself from scratch, but I do know that on personalization software services like Personyze, there is a widget for it, you simply upload locations and the visitor is automatically shown the location that is closest to them. You can also offer them alternative locations nearby, etc. Worth checking out, if that's your use case.

Riley
  • 1
0

If anyone needs a react solution I created this child component:

export default function Map(props) {
    const address = `${props.winery.address} ${props.winery.city}, ${props.winery.state} ${props.winery.zip}`;
    const src     = `https://maps.google.com/maps?&q="+${address}"&output=embed`;
    const Embed = () => { 
        return(
            <div>
                <iframe 
                    width="100%" 
                    height="450"
                    allowFullScreen="" 
                    loading="lazy" 
                    referrerPolicy="no-referrer-when-downgrade" 
                    src={src}
                >
                </iframe>
            </div>
        );
    }

    return(
        <>
            <Embed />
        </>
    )
}

You may need to adjust the props, the object I passed had all the necessary data.

user3330820
  • 501
  • 2
  • 7
  • 17