Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Google maps with user defined location

Featured Replies

Hello,

Can anyone advise me on how to implement google maps with a user defined location, in other words a map which would allow the viewer to click and place a marker as their location. I plan to have a contact form which would include the viewers location they mark in google maps. I couldnt find anything in the google examples but i do have a live example here. How has this been done ?

Thanks

Read the documentation. If you read through it, you'll learn how to work with the Maps API.

 

There is no cut and paste with Google Maps API, you kinda just have to read through and work it out for yourself. If you have a basic understanding of Javascript it shouldn't be too difficult :)

 

http://code.google.com/apis/maps/documentation/javascript/tutorial.html

  • Author

Read the documentation. If you read through it, you'll learn how to work with the Maps API.

 

There is no cut and paste with Google Maps API, you kinda just have to read through and work it out for yourself. If you have a basic understanding of Javascript it shouldn't be too difficult :)

 

http://code.google.com/apis/maps/documentation/javascript/tutorial.html

 

Thanks for your reply :-).

 

I have however read through the google documentation and couldnt find anything remotely like what im looking for. Obviously it can be done though as the example aboves proves it so what api are they using ?

They're using v2.0, which is deprecated, so eventually it will be turned off altogether. So you're best off using v.3.0.

 

You're not reading the documentation properly, then, because it includes examples that do what you want. In fact, the following even goes one step further, removing the need for someone to enter their address and finding it for them using Geolocation:

 

http://code.google.com/apis/maps/documentation/javascript/examples/map-geolocation.html

 

If you don't want that though, this is the one:

 

http://code.google.com/apis/maps/documentation/javascript/examples/geocoding-simple.html

 

Now, that doesn't allow the user to click on the map - but what it would do is plot a marker based on the address they've entered into your form, which saves them time anyway.

 

If you absolutely want it so the user places a marker, read this:

 

http://code.google.com/apis/maps/documentation/javascript/events.html

 

It tells you how to use Javascript to interpret a user click action.

 

Here's an example, though you will want to change it to disallow multiple locations:

 

http://code.google.com/apis/maps/documentation/javascript/examples/event-arguments.html

 

You'll also need to think about how you pass that markers location through your form as I presume you will need to know where they've clicked? If I was you I'd do this by writing the Javascript so it takes the Longitude/Latitude of the markers location and inserts that info into a hidden text field when the user clicks. You'd then be able to use that to find where they placed the marker.

 

Hope that all makes sense. Like I said there's no "out of the box" ready-made way to do what you want, you're gonna need to brush up on your javascript and figure most of it out for yourself. Gmaps API is really hard though so I feel for you! If I could help more I would. Good luck!

  • Author

Thanks Mike,

 

This looks to be just what i need, fantastic. I guess you just need to know what to look for as i never would have guessed to look under events.

 

I'll have a look through this now and give it a go, thanks again ;-).

  • Author

I've spent the past few days on this and im so close its just silly ...

 

Basically what i now have are two forms, form1 is a simple 1 field form where the user inputs the address and is forwarded to form2 where google maps is situated. Using GET i have managed to pass the address input in form1 into the url and javascript then gets that address and inserts it into form2's address field.

 

This all works fine, the address input in form1 appears in form2 and it works as id expect BUT the address isnt automatically selected in form2. I think the problem is that im using jquery to search the address which requires a onclick function for google to find the address.

 

How would i go about making the address auto select and showing the location on the map.

 

Here is a working example of what i have so far link

 

My basic code consists of the following:

 

form1

 

<form action="contact.html" id="FoxForm" name="FoxForm" class="foxform"><label>Address: </label><input type="text" name="address" id="address">
 <p><input type="submit" value="Submit"></p>
</form>

 

form2

 

<form action="/contact.html#cid_472" method="post" class="foxform" name="FoxForm" id="FoxForm" enctype="multipart/form-data">
<label>Address: </label><input type="text" value="" name="address" id="address">
<div id="map_canvas" style="width:300px; height:300px"></div>
<label>latitude</label><input type="text" name="_b011a4587ceb7be7c17607311b5b187d" title="latitude" value="" id="latitude" class="foxtext"></div>
<label>longitude</label><input type="text" name="_905b11bc9b7eb767671d28ab6020970b" title="longitude" value="" id="longitude" class="foxtext"></div>
<button name="cid_472" type="submit" class="foxbutton">
<span>Submit</span>
</button>
</form>

 

main.js (for gmaps and form2)

 

//Useful links:
// http://code.google.com/apis/maps/documentation/javascript/reference.html#Marker
// http://code.google.com/apis/maps/documentation/javascript/services.html#Geocoding
// http://jqueryui.com/demos/autocomplete/#remote-with-cache

var geocoder;
var map;
var marker;

function initialize(){
//MAP
 var latlng = new google.maps.LatLng(41.659,-4.714);
 var options = {
   zoom: 16,
   center: latlng,
   mapTypeId: google.maps.MapTypeId.SATELLITE
 };

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

 //GEOCODER
 geocoder = new google.maps.Geocoder();

 marker = new google.maps.Marker({
   map: map,
   draggable: true
 });

}

$(document).ready(function() { 

 initialize();

 $(function() {
   $("#address").autocomplete({
     //This bit uses the geocoder to fetch address values
     source: function(request, response) {
       geocoder.geocode( {'address': request.term }, function(results, status) {
         response($.map(results, function(item) {
           return {
             label:  item.formatted_address,
             value: item.formatted_address,
             latitude: item.geometry.location.lat(),
             longitude: item.geometry.location.lng()
           }
         }));
       })
     },
     //This bit is executed upon selection of an address
     select: function(event, ui) {
       $("#latitude").val(ui.item.latitude);
       $("#longitude").val(ui.item.longitude);
       var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
       marker.setPosition(location);
       map.setCenter(location);
     }
   });
 });

 //Add listener to marker for reverse geocoding
 google.maps.event.addListener(marker, 'drag', function() {
   geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
     if (status == google.maps.GeocoderStatus.OK) {
       if (results[0]) {
         $('#address').val(results[0].formatted_address);
         $('#latitude').val(marker.getPosition().lat());
         $('#longitude').val(marker.getPosition().lng());
       }
     }
   });
 });

});

 

js for form2 which gets the input from form1

 

<script LANGUAGE="JavaScript"><!--
function replace(string,text,by) {
   // Replaces text with by in string
   var i = string.indexOf(text), newstr = '';
   if ((!i) || (i == -1))
       return string;
   newstr += string.substring(0,i) + by;
   if (i+text.length < string.length)
       newstr += replace(string.substring(i+text.length,string.length),text,by);
   return newstr;
}

var passed = replace(replace(location.search.substring(1),"+"," "),"=","&");

function split(string,text) {
   var strLength = string.length, txtLength = text.length;
   if ((strLength == 0) || (txtLength == 0)) return;
   var i = string.indexOf(text);
   if ((!i) && (text != string.substring(0,txtLength))) return;
   if (i == -1) {
       splitArray[splitIndex++] = string;
       return;
   }
   splitArray[splitIndex++] = string.substring(0,i);
   if (i+txtLength < strLength)
       split(string.substring(i+txtLength,strLength),text);
   return;
}

//--></SCRIPT>

<script LANGUAGE="JavaScript1.1"><!--
function split(string,text) {
   splitArray = string.split(text);
   splitIndex = splitArray.length;
}
//--></SCRIPT>

<script LANGUAGE="JavaScript"><!--
var splitIndex = 0, splitArray = new Object();

split(passed,'&');

for (var i=0; i < splitIndex; i=i+2) {
   if (splitArray[i] == 'address')
       document.formname.address.value = unescape(splitArray[i+1]);
   if (splitArray[i] == 'textareaname')
       document.formname.textareaname.value = unescape(splitArray[i+1]);
   if (splitArray[i] == 'passwordname')
       document.formname.passwordname.value = unescape(splitArray[i+1]);
   if (splitArray[i] == 'selectname')
       document.formname.selectname.selectedIndex = splitArray[i+1];
   if (splitArray[i] == 'multipleselectname')
       document.formname.multipleselectname.options[splitArray[i+1]-0].selected = true;
   if (splitArray[i] == 'checkboxname')
       document.formname.checkboxname.checked = true;
   if (splitArray[i] == 'radioname')
       document.formname.radioname[splitArray[i+1]].checked = true;
}
//--></SCRIPT>

Have you tried echo'ing the address the user inputs into a hidden form field on page 2? Then just use your maps code as usual, pulling the address from that field.

 

Edit: Bare in mind that'd be POST, not GET.

Edited by brightonmike

  • Author

Have you tried echo'ing the address the user inputs into a hidden form field on page 2? Then just use your maps code as usual, pulling the address from that field.

 

Edit: Bare in mind that'd be POST, not GET.

 

Thanks again for your reply Mike.

 

Im not really much of a coder when it comes to javascript so this is a bit all over the place, im having a tough time understanding it all. I've actually put this together from various scripts i've found so its like frankinsteins code :p.

 

Im not familiar with the POST method and seeing its taken me this long to figure out GET i think id rather just stick with GET. I think the principal is basically the same anyway only with GET the fields are brought from the url.

 

The main issue is the autocomplete thats going on, when you type an address a dropdown of results appears and you have to select one for the googlemaps to show it on the map. So currently typing and selecting an address on form1 is pointless as your still having to select the address on form2. Maybe if i could disable the autofill it would work.

 

The autocomplete dropdown isnt even needed so the simpler it is the better really.

Thanks again for your reply Mike.

 

Im not really much of a coder when it comes to javascript so this is a bit all over the place, im having a tough time understanding it all. I've actually put this together from various scripts i've found so its like frankinsteins code :p.

 

Im not familiar with the POST method and seeing its taken me this long to figure out GET i think id rather just stick with GET. I think the principal is basically the same anyway only with GET the fields are brought from the url.

 

The main issue is the autocomplete thats going on, when you type an address a dropdown of results appears and you have to select one for the googlemaps to show it on the map. So currently typing and selecting an address on form1 is pointless as your still having to select the address on form2. Maybe if i could disable the autofill it would work.

 

The autocomplete dropdown isnt even needed so the simpler it is the better really.

 

 

Why would you need the field again on the second page?! You're over-complicating things.

 

And...I'm sorry but if you insist on using GET, I can't really help you, as I only have experience doing this using POST.

 

 

Also, you can't really use AutoComplete for addresses so far as I know....

This is how I do it.

 

<input type="text" id="from" name="from" value="" placeholder="Enter airport name, city or ICAO" class="required" AUTOCOMPLETE=OFF>

 

This value is then echo'd on the following page. Because with my setup, the form is submitted BEFORE the map, I hide the form field. However as you're submitting AFTER the map, just use one of your existing fields.

 

<input id="address1" style="visibility:hidden" type="textbox" value="<?php echo $_POST["from"]; ?>">

 

I loop through three addresses and GeoCode them, you'll only be using one so you don't need the loop, but here it is anyway.

 

locations = [document.getElementById('address1').value, document.getElementById('address3').value, document.getElementById('address2').value];

 

 

function addMarkers(locations) {

   var geocoder = new google.maps.Geocoder();



   // Loop through locations array

   for (var i = 0; i < locations.length; i++) {

       // Use geocode service to find latlng

       geocoder.geocode( { 'address': locations[i] }, drawGeodesic(locations[i], i));

   }



}

 

And that, works perfectly, and is pretty much identical in function to what you're trying to do.

Edited by brightonmike

  • Author

Correct me if im wrong but the field is required on the second form for google maps to work. If i could get it to work without the address there id go for it but i havent been able to so far. Without an address no map / location is shown.

 

The simpler it is the better.

 

Heres the partial script im using

 

http://tech.cibul.net/geocode-with-google-maps-api-v3/

 

http://gmap3.net/examples/address-lookup.html

 

I can use POST if preferred but i really dont know how to go about it other than changing the method to POST.

 

Also the autocomplete seems to be as standard for the google map search so it definately can be used. Id prefer it wasnt though as the autocomplete is whats messing this up, atleast i think.

  • Author

I should also point out that i am using POST for the main form where google maps is, the first form only uses GET to pass the address entered.

Correct me if im wrong but the field is required on the second form for google maps to work. If i could get it to work without the address there id go for it but i havent been able to so far. Without an address no map / location is shown.

 

The simpler it is the better.

 

Heres the partial script im using

 

http://tech.cibul.net/geocode-with-google-maps-api-v3/

 

http://gmap3.net/examples/address-lookup.html

 

I can use POST if preferred but i really dont know how to go about it other than changing the method to POST.

 

Also the autocomplete seems to be as standard for the google map search so it definately can be used. Id prefer it wasnt though as the autocomplete is whats messing this up, atleast i think.

 

 

If someone has already entered their address, you do NOT need to show the field again. You're gonna confuse people into thinking they need to enter it again. Hide it. You can echo it in your text though if you wish to show them what they entered.

 

Read above, I've told you how to do it.

Edited by brightonmike

  • Author

Sorry Mike but i seem to be having trouble understanding your code. I've implemented this on the working example but it doesnt appear to do anything so im assuming i have done something wrong.

 

Am i correct in thinking

 

<input type="text" id="from" name="from" value="" placeholder="Enter airport name, city or ICAO" class="required" AUTOCOMPLETE=OFF>

 

goes on form1 and i change form1's method to POST

 

<input id="address1" style="visibility:hidden" type="textbox" value="<?php echo $_POST["from"]; ?>">

 

and that the above goes on form2. How would the first forms input be echoed here though, when i submit form1 the field value on form2 stays at <?php echo $_POST["from"]; ?> so im assuming something else would need to go with this.

 

Finally the javascript, what would be the correct way of formatting this and do i need my existing functions. Heres what i have with your changes.

 

//Useful links:
// http://code.google.com/apis/maps/documentation/javascript/reference.html#Marker
// http://code.google.com/apis/maps/documentation/javascript/services.html#Geocoding
// http://jqueryui.com/demos/autocomplete/#remote-with-cache

var geocoder;
var map;
var marker;

function initialize(){
//MAP
 var latlng = new google.maps.LatLng(41.659,-4.714);
 var options = {
   zoom: 16,
   center: latlng,
   mapTypeId: google.maps.MapTypeId.SATELLITE
 };

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

 //GEOCODER
 geocoder = new google.maps.Geocoder();

 marker = new google.maps.Marker({
   map: map,
   draggable: true
 });

locations = [document.getElementById('address1').value, document.getElementById('address3').value, document.getElementById('address2').value];

}

function addMarkers(locations) {

   var geocoder = new google.maps.Geocoder();



   // Loop through locations array

   for (var i = 0; i < locations.length; i++) {

       // Use geocode service to find latlng

       geocoder.geocode( { 'address': locations[i] }, drawGeodesic(locations[i], i));

   }



}

$(document).ready(function() { 

 initialize();

 $(function() {
   $("#address").autocomplete({
     //This bit uses the geocoder to fetch address values
     source: function(request, response) {
       geocoder.geocode( {'address': request.term }, function(results, status) {
         response($.map(results, function(item) {
           return {
             label:  item.formatted_address,
             value: item.formatted_address,
             latitude: item.geometry.location.lat(),
             longitude: item.geometry.location.lng()
           }
         }));
       })
     },
     //This bit is executed upon selection of an address
     select: function(event, ui) {
       $("#latitude").val(ui.item.latitude);
       $("#longitude").val(ui.item.longitude);
       var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
       marker.setPosition(location);
       map.setCenter(location);
     }
   });
 });

 //Add listener to marker for reverse geocoding
 google.maps.event.addListener(marker, 'drag', function() {
   geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
     if (status == google.maps.GeocoderStatus.OK) {
       if (results[0]) {
         $('#address').val(results[0].formatted_address);
         $('#latitude').val(marker.getPosition().lat());
         $('#longitude').val(marker.getPosition().lng());
       }
     }
   });
 });

});

/sigh.

 

I've told you not to use the loop, but you are. My code is purely there as an example, not for you to just copy and paste. Doesn't work like that. You need to grab the value from the input on page 2 and Geocode it.

 

If you are using method=POST on the first form it should echo the value fine on page two providing you are using PHP. It won't work now because your second page is just HTML. It needs to be a PHP page. PHP won't work on .html.

 

Save pasting my full code, which I won't and can't do, this is about as much guidance as I can give to you, sorry!

Essentially, POST the value to the second page which needs to be a PHP page.

 

Echo the value in a hidden input field on the second page.

 

Pull that value into your Google Maps code, Geocode, plot on the map.

 

Think about it, if you can tap an address into an input and plot it on the map, then that's essentially what Page 2 does but instead of a field you can see and type in, it's a hidden field with the value from the first page.

 

You'll want to use onLoad so it shows up when page 2 loads.

Edited by brightonmike

Right, cos today I'm feeling super generous, I've done it for you.

 

This is your code for the first form. I've left the id's blank, change as appropriate for your styling.

 

<form id="" name="" action=".php" method="post">
<input type="text" id="address" name="address" value="">
<button id="" type="submit">Submit</button>
</form>

 

 

Secondly, your second page MUST be PHP, i.e. the filename ends .php not .html. This code then goes into your head:

 

<script type="text/javascript">
 var geocoder;
 var map;
 function initialize() {
   geocoder = new google.maps.Geocoder();
   var latlng = new google.maps.LatLng(-34.397, 150.644);
   var myOptions = {
     zoom: 8,
     center: latlng,
     mapTypeId: google.maps.MapTypeId.ROADMAP
   }
   map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
 }

 function codeAddress() {
   var address = document.getElementById("address").value;
   geocoder.geocode( { 'address': address}, function(results, status) {
     if (status == google.maps.GeocoderStatus.OK) {
       map.setCenter(results[0].geometry.location);
       var marker = new google.maps.Marker({
           map: map, 
           position: results[0].geometry.location
       });
     } else {
       alert("Geocode was not successful for the following reason: " + status);
     }
   });
 }
</script>

 

You then need to have your map initialize on load, which you do by changing this:

 

<body>

 

To this: ON THE SECOND PAGE.

 

<body onload="initialize();"> 

 

 

Then, somewhere, anywhere on the second page, put this:

 

 

<input id="address" style="visibility:hidden" type="textbox" value="<?php echo $_POST["address"]; ?>">

 

That box will not show, it's hidden by CSS, so you don't need to worry where it is, as long as it's between the body tags.

 

 

That definitely, 100% works. The only thing it won't do is plot a marker on the location entered. You'll need to work that out for yourself. Just like ALL the above, how to plot a marker is documented in the Maps v3 API.

 

Please consider re-writing this code yourself rather than purely copy and pasting, it would be worth your time understanding what I've done here and how.

 

Good luck, and a few plus ones would be nice :p

  • Author

Thank you Mike,

 

This is a huge help and im all for doing this myself, its the only way i'll ever learn javascript so im not about to give up but wow is it frustrating. I've never worked with javascript like this so please go easy on me and dont laugh too much :).

 

Anyway, so far with the help of your function i have managed to add a marker when you left click, only if you click again another marker gets added so im ending up with more than one marker. Not quite sure why this is, i read the google api and it said if i use addMarker rather than addMarkers it would only add one but obviously thats not the case. I cant seem to get the geolocation working either but im going to look at the api on that shortly to see if i can figure out whats wrong.

 

If someone would kindly just check over my code so far, to see if im going wrong anywhere that would be great.

 

var map;
var marker;
var geocoder;

 function initialize() {
   geocoder = new google.maps.Geocoder();
   var latlng = new google.maps.LatLng(41.659,-4.714);
   var myOptions = {
     zoom: 12,
     center: latlng,
     mapTypeId: google.maps.MapTypeId.SATELLITE
   }
   map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);  

 google.maps.event.addListener(map, 'click', function(event) {
   addMarker(event.latLng);
 });

 }

// adds marker

function addMarker(location) {
 marker = new google.maps.Marker({
   position: location,
   map: map,
           draggable: true
 });
 marker.push(marker);
}

// Does something

 function codeAddress() {
   var address = document.getElementById("address").value;
   geocoder.geocode( { 'address': address}, function(results, status) {
     if (status == google.maps.GeocoderStatus.OK) {
       map.setCenter(results[0].geometry.location);
       var marker = new google.maps.Marker({
           map: map, 
           draggable: true,
           position: results[0].geometry.location
       });
     } else {
       alert("Geocode was not successful for the following reason: " + status);
     }
   });

 marker.setMap(map);  

 }

 

Heres my new example link

 

Im still not fully understanding whats going on in the javascript but i think im slowly starting too ...

 

Oh and Mike i have given you plenty of plus's for your help, thanks again ;).

Edited by gfxpixeldesigns

I don't think that code is right. Have you tried just using what I posted?

 

You'll need to remove the codeAddress function.

 

I'm getting confused with what you want to do. On one hand, you've got an address box which the user inputs an address, which is GeoCoded, and the map then shows that location - on the other hand you've got a map where the user has to click onto the map to add a marker?

 

With regards to the latter, I don't have any experience doing that so I can't help you. If you want to do the former, you need to use the code I posted above.

 

Thanks for the plus ones :)

Edited by brightonmike

  • Author

I have no doubt its wrong somewhere, your unedited code doesnt appear to work either. It just loads the map without doing anything from what i can see.

 

What i want to do is identical to link

 

So basically form 1 has the address field where they enter a postcode, that is then passed onto form 2. Form 2 then uses the postcode / address to find / geocode the location and zooms into the map location. The user then places a marker over there roof or if its easier google can add the marker to the approx location and the user can then drag it to there roof.

So basically form 1 has the address field where they enter a postcode, that is then passed onto form 2. Form 2 then uses the postcode / address to find / geocode the location and zooms into the map location. The user then places a marker over there roof or if its easier google can add the marker to the approx location and the user can then drag it to there roof.

 

 

The code I have given you does exactly what you've said in the bold. After the bold, I wouldn't know how to do that, sorry.

 

But I know for a fact that the code I posted works, because a] I have it working on a commercial website and b] it's identical code that is on Googles own developer pages.

 

Please bare in mind that the code I have given you does not place a marker on the location.

Edited by brightonmike

Sorry buddy, but if it's not working for you, I don't know what you want me to do, because not only does it work perfectly for me, but the exact same code works here too:

 

code.google.com/apis/maps/documentation/javascript/examples/geocoding-simple.html

 

The only difference is your map is placed inside your form, I don't know why you've done that. But basically they're the same code.

 

Not much else I can do tbh.

Edited by brightonmike

  • Author

Thanks again Mike,

 

I think the problem is that the example you've shown uses onclick so for it to work i need this:

 

<input type="button" onclick="codeAddress()" value="Geocode">

  • Author

So i think the issue now is how do i execute your codeAddress function without the onlick.

I don't use onClick. My address values are entered by the user on a previous page, then passed onto a second page where they are echo'd into hidden inputs, Geocoded and a map is plotted.

 

Edit: A very early example of my code: http://jsfiddle.net/KYhPF/5/

 

The difference between the code in that link is that the map plots based on data entered into the two boxes. On my real working example, those inputs are populated with data from the form on the previous page. To do this, all I did was:

 

<input id="address1" style="visibility:hidden" type="textbox" value="<?php echo $_POST["from"]; ?>">
<input id="address2" style="visibility:hidden" type="textbox" value="<?php echo $_POST["to"]; ?>">

 

I then remove the onclick function and use this instead:

 

<body onload="initialize();"> 

 

 

Don't use any of that code, it has functionality that is not appropriate to your requirements. Anyway, it won't work for you.

Edited by brightonmike

  • Author

With a couple changes this appears to be working fine. Am i okay to use this as a base ?

Remove the array. You don't need it.

 

You really should re-write the code, I wrote that and copying what I wrote won't teach you how to do it.

 

Not that I can stop you!

 

Edit: Also, that code does not have the functionality of the user clicking to add a marker. If you really need that, you will have to code from scratch because most of that code will need to be changed to accommodate that functionality.

 

The array is this line:

 

locations = [document.getElementById('address1').value, document.getElementById('address2').value];

 

You're geocoding one address, not multiple addresses, so you don't need an array.

 

Use the normal variables line:

 

var address = document.getElementById("address").value;

 

You'll then need to re-write some of the code so it's working with the variable "address" and not trying to geocode the now non-existent array.

Edited by brightonmike

  • Author

No worries thats why i asked :).

 

I have changed it to handle one address though and it does actually work. I'm just trying to do something similar using the simple google example.

You've just altered the array, your code is still handling an array, just of one location. No point using arrays when you're only using one variable.

 

Basically a lot of that code is written to deal with an array of locations.

I'm trying to sort out the code but JSFIDDLE has slowed to an absolute halt so I can't help you atm, sorry.

http://jsfiddle.net/brightonmike/trUYE/

 

All you need to do now is replace the value of the input with the PHP echo, echoing the value from page 2.

 

That's all the code you need. Remove the submit button. That's just there to show it works.

 

And by the way, this is the same code I originally posted, I just removed the codeAddress function.

Edited by brightonmike

  • Author

Cheers for that ;)

 

I've spent the last few hours reading through javascript tutorials as well as the google api trying to figure out what everything does. I still dont understand all of it but i now have a much better understanding of it all.

 

Just one quick question, simply put what does <body onload="initialize()"> do exactly ? I cant find a definite answer on the web but i would have to assume it loads the javascript the moment the page loads. Is that right ?

 

Your code did indeed work straight away and does everything i need but as i want a few extra's i've made some minor changes.

 

Firstly i needed the map to zoom on the location and the marker to be draggable so i've done this with

 

map.setZoom(18);

 

draggable: true

 

The rest seems to be identical to the simple google example so i've left that as it is, the only expection to this being the jquery autocomplete and reverse geocoding for the marker. I dont really need the autocomplete but i figure its something different and the end user will appreciate it so i have added it.

 

The reverse geocoding is quite important to me though as without it the latitude / longitude fields wont update when the user drags the marker so this is completely necessary.

 

I've implemented it using

 

  //Add listener to marker for reverse geocoding
 google.maps.event.addListener(marker, 'drag', function() {
   geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
     if (status == google.maps.GeocoderStatus.OK) {
       if (results[0]) {
         $('#address').val(results[0].formatted_address);
         $('#latitude').val(marker.getPosition().lat());
         $('#longitude').val(marker.getPosition().lng());
       }
     }
   });
 });

 

but for some reason this doesnt appear to be working. I've debugged it in firebug and cant find any issues so im presuming im using the wrong identifier or something insanely silly !

 

Could somebody have a quick look over my code to see if im going wrong anywhere.

 

The entire code for form2 is:

 

<head>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.1.custom.min.js"></script>
<script type="text/javascript">
 var geocoder;
 var map;
 var marker;

 function initialize() {
   geocoder = new google.maps.Geocoder();
 var latlng = new google.maps.LatLng(41.659,-4.714);
   var options = {
     zoom: 8,
     center: latlng,
   mapTypeId: google.maps.MapTypeId.SATELLITE
   }
   map = new google.maps.Map(document.getElementById("map_canvas"), options);
     var address = document.getElementById("address").value;
   geocoder.geocode( { 'address': address}, function(results, status) {

     if (status == google.maps.GeocoderStatus.OK) {
       map.setCenter(results[0].geometry.location);
       var marker = new google.maps.Marker({
           map: map,
           draggable: true,
           position: results[0].geometry.location
       });

   map.setZoom(18);

     } else {
       alert("Geocode was not successful for the following reason: " + status);
     }
   });

   $("#address").autocomplete({
     //This bit uses the geocoder to fetch address values
     source: function(request, response) {
       geocoder.geocode( {'address': request.term }, function(results, status) {
         response($.map(results, function(item) {
           return {
             label:  item.formatted_address,
             value: item.formatted_address,
             latitude: item.geometry.location.lat(),
             longitude: item.geometry.location.lng()
           }
         }));
       })
     },
     //This bit is executed upon selection of an address
     select: function(event, ui) {
       $("#latitude").val(ui.item.latitude);
       $("#longitude").val(ui.item.longitude);
       var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
       marker.setPosition(location);
       map.setCenter(location);
     }
   });

 //Add listener to marker for reverse geocoding
 google.maps.event.addListener(marker, 'drag', function() {
   geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
     if (status == google.maps.GeocoderStatus.OK) {
       if (results[0]) {
         $('#address').val(results[0].formatted_address);
         $('#latitude').val(marker.getPosition().lat());
         $('#longitude').val(marker.getPosition().lng());
       }
     }
   });
 });

 }

</script>
</head>

<body onload="initialize()">

<form class="geocode" method="post">
   <input id="address" style="visibility: hidden;" type="textbox" value="<?php echo $_POST["address"]; ?>">
   <input type="button" style="visibility: hidden;" value="Geocode" onclick="initialize()">
   <div id="map_canvas" style="width:300px; height:300px"></div><br/>
   <label>latitude: </label><input id="latitude" name="latitude" type="text" value="<?php echo $_POST["latitude"]; ?>"/><br/>
   <label>longitude: </label><input id="longitude" id="longitude" type="text"value="<?php echo $_POST["longitude"]; ?>"/>

   <p><label>Name:</label> <input type="text" name="name"></p>
   <p><label>Street Address:</label> <input type="text" name="street_address"></p>
   <p><label>City:</label> <input type="text" name="state"></p>
   <p><label>State:</label> <input type="text" name="state"></p>
   <p><label>Postal Code:</label> <input type="text" name="postal_code"></p>
   <p><label>Country:</label> <input type="text" name="country"></p>
   <p><input type="submit" value="Submit"></p>


</form>

</body>

onLoad tells the browser to execute the function when the page loads.

 

The function in this case being initialize - so yes you're right.

 

I haven't used their reverse geocoding API but I would imagine rather than tacking it onto the end, you're going to need to directly edit the code I gave you to add in the reverse geocoding.

 

I can't help you with that I'm afraid - so at this point I shall duck out of the thread. Hopefully someone else can help.

 

Good luck!

Edited by brightonmike

  • Author

No worries Mike and thank you again for all your help.

 

You have most certainly made me a little more knowledgeable on the javascript side and i hope the code will be of use to someone else as well.

 

I'm still non the wiser on the reverse geocoding, according to the api it should just work on the end there but im wondering if it needs to be inside its own function or something.

 

Anyway i'm giving up for tonight as i have a huge headache but i will tackle this again tomorrow.

  • Author

Pure determination has got me there in the end and i now have a fully functioning map script. Not only that but im proud to say that i coded the majority of this myself :).

 

For anyone interested here is the working example http://rayoflightes.com/gmaps/form1.php

 

My js code is:

 

var geocoder = new google.maps.Geocoder();

function geocodePosition(pos) {
 geocoder.geocode({
   latLng: pos
 }, function(responses) {
   if (responses && responses.length > 0) {
     updateMarkerAddress(responses[0].formatted_address);
   } else {
     updateMarkerAddress('Cannot determine address at this location.');
   }
 });
}

function updateMarkerStatus(str) {
 document.getElementById('markerStatus').innerHTML = str;
}

function updateMarkerPosition(latLng) {
 document.getElementById('latitude').value = [
   latLng.lat()
 ];
 document.getElementById('longitude').value = [
   latLng.lng()
 ];
}



function initialize() {

         var address = document.getElementById("address").value;

 var latLng = new google.maps.LatLng(-34.397, 150.644);
 var map = new google.maps.Map(document.getElementById('mapCanvas'), {
   zoom: 12,
   center: latLng,
   mapTypeId: google.maps.MapTypeId.SATELLITE
 });

   geocoder.geocode( { 'address': address}, function(results, status) {

     if (status == google.maps.GeocoderStatus.OK) {
       map.setCenter(results[0].geometry.location);
       var marker = new google.maps.Marker({
           map: map,
           draggable: true,
           position: results[0].geometry.location,
       });

   map.setZoom(18);

 // Update current position info.
 updateMarkerPosition(latLng);
 geocodePosition(latLng);

 // Add dragging event listeners.
 google.maps.event.addListener(marker, 'dragstart', function() {
   updateMarkerAddress('Dragging...');
 });

 google.maps.event.addListener(marker, 'drag', function() {
   updateMarkerStatus('Dragging...');
   updateMarkerPosition(marker.getPosition());
 });

 google.maps.event.addListener(marker, 'dragend', function() {
   updateMarkerStatus('Drag ended');
   geocodePosition(marker.getPosition());
 });

/* When geocoding "fails", see if it was because of over quota error: */
           } else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
             wait = true;
             setTimeout("wait = false", 1000);

           } else {
             alert("Geocode was not successful for the following reason: " + status);
           }
   });


}

// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);

 

Enter your address in the first form, submit it and move the marker, you should see the long / lat fields updating as you move.

 

Note that the above will be changing, for starters i need to add some styling and get rid / hide any unecessary fields. Im just glad its working, finally ! Another perhaps more important step is checking this for errors and testing in different browsers.

 

I would appreciate it if someone would have a quick scan over my code for errors. Im not sure about the else if statement myself, it doesnt look quite right but its working so i've left it.

Edited by gfxpixeldesigns

Huzzah, a fellow Google Maps conqueror :)

 

Btw, if you want, you can control the colours of the map to distinguish it from the usual and make it fit in with your site designs better.

 

One of the advantages of API v3!

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.