How do I use Google Maps geocoder.getLatLng() and store its result in a database?
Asked Answered
S

5

11

Hey everybody! Im trying to use getLatLng() to geocode a list of postal/zip codes and store the generated point in the database to be placed on a map later. This is what I've got so far:

 $(".geocodethis").click(function () {
    var geocoder = new GClientGeocoder();
    var postalCode = $(this).siblings(".postal").val();
    var id = $(this).siblings(".id").val();

    geocoder.getLatLng(postalCode, function (point) {
        if (!point) {
            alert(postalCode + " not found");
        } else {
            alert(point);
            var serializedPoint = $.param(point);                
            //Geocode(id, point);
        }
    });

});

function Geocode(id, point) {
    alert(point);
    $.post("/Demographic/Geocode/" + id, point, function () {
        alert("success?");
    });
}

but I'm getting this.lat is not a function in my error console when i try to serialize the point object or use it in $.post()

From my research, I understand that geocoder.getLatLng() is asynchronous, how would that affect what I'm trying to do? I'm not running this code in a loop, and I'm trying to post the point using the anonymous callback function.

How can I save the information from point to use later?

Update

Creating a marker and trying to post that still results in the this.lat is not a function in the error console.

$(".geocodethis").click(function () {
        var geocoder = new GClientGeocoder();
        var postalCode = $(this).siblings(".postal").val();
        var id = $(this).siblings(".id").val();

        geocoder.getLatLng(postalCode, function (point) {
            if (!point) {
                alert(postalCode + " not found");
            } else {
                alert(point);
                var marker = new GMarker(point);

                $.post("/Demographic/Geocode/" + id, marker, function () {
                    alert("success?");
                });
            }
        });

    });

** Another Update **

I really need to save the geocoded address for later, even if I store the latitude/longitude values in my database and remake the marker when I'm ready to put it onto a map. Again, serializing or posting - seemingly using the point in any way other than in google maps functions gives the this.lat is not a function exception in my error log.

I'm using asp.net mvc - are there any frameworks out there that would make this easier? I really need help with this. Thanks.

Saintebeuve answered 25/4, 2011 at 19:57 Comment(1)
#4557102Heraclid
C
12

If your stuck for 2 days maybe a fresh v3 start would be a good thing, this snipped does a similair job for me...

          function GetLocation(address) {
          var geocoder = new google.maps.Geocoder();
          geocoder.geocode({ 'address': address }, function (results, status) {
              if (status == google.maps.GeocoderStatus.OK) {
                  ParseLocation(results[0].geometry.location);

              }
              else
                alert('error: ' + status);

          });
      }

  }

  function ParseLocation(location) {

      var lat = location.lat().toString().substr(0, 12);
      var lng = location.lng().toString().substr(0, 12);

      //use $.get to save the lat lng in the database
      $.get('MatchLatLang.ashx?action=setlatlong&lat=' + lat + '&lng=' + lng,
            function (data) {
                // fill textboss (feedback purposes only) 
                //with the found and saved lat lng values
                $('#tbxlat').val(lat);
                $('#tbxlng').val(lng);
                $('#spnstatus').text(data);


            });
    }
Conure answered 28/4, 2011 at 20:18 Comment(3)
any reason you use $.get() instead of $.post()Saintebeuve
I'm linking the v3 google maps using <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> is this correct? I'm still getting the this.lat() is not a function.Saintebeuve
"any reason you use $.get() instead of $.post() " Not realy, just because its only a small amount of data...Conure
E
2

Have you tried this?

$(".geocodethis").click(function () {
    var geocoder = new GClientGeocoder();
    var postalCode = $(this).siblings(".postal").val();
    var id = $(this).siblings(".id").val();

    geocoder.getLatLng(postalCode, function (point) {
        if (!point) {
            alert(postalCode + " not found");
        } else {
            alert(point);
            var marker = new GMarker(point);
            map.addOverlay(marker);
            obj = {lat: marker.position.lat(),
                   lng: marker.position.lng()};
            $.post("/Demographic/Geocode/" + id, obj, function () {
                alert("success?");
            });
        }
    });

});

I haven't used V2 in a long time, so I'm not sure about the exact syntax, but the point is to create an object from the information you need (lat/lng) and serialize that.

Also, an upgrade to V3 is much recommended, if plausible.

Endopeptidase answered 28/4, 2011 at 21:37 Comment(0)
T
0

You need to set a marker on the map, which takes a lat/long. You can save that info however you want or display immediately. (Code truncated for demo purpose)

map = new google.maps.Map(document.getElementById("Map"), myOptions);
geocoder.geocode({ 'address': address }, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {      
        var marker = new google.maps.Marker({
            position: results[0].geometry.location
        });
        marker.setMap(map);
    }
}

UPDATE (FOR v2)

$(".geocodethis").click(function () {
    var geocoder = new GClientGeocoder();
    var postalCode = $(this).siblings(".postal").val();
    var id = $(this).siblings(".id").val();

    geocoder.getLatLng(postalCode, function (point) {
        if (!point) {
            alert(postalCode + " not found");
        } else {
            map.setCenter(point, 13);
            var marker = new GMarker(point);
            map.addOverlay(marker);
        }
    });

});
Thiazole answered 25/4, 2011 at 20:9 Comment(15)
i think he's using google map v2 api based on the GClientGeocoderHeraclid
Okay, so results would be point for me, and its an array? So results[0] would be Y, and results[1] would be X? Because it isn't allowing me to save results. Or do I save the marker?Saintebeuve
Sorry, thanks to @kjy112 who noticed you are using v2. However, for v3 the results[0] is simply the top result for the search and the results[0].geometry.location is the full lat/lng of the top result.Thiazole
ah, okay - so...what do I do for v2?Saintebeuve
:( I'm still getting this.lat is not a functionSaintebeuve
No where in your's or my code is there a this.lat. Are you sure it is not somewhere else causing the issue. You a JS debugger to find the offending line.Thiazole
its coming from line 278 in http://maps.gstatic.com/intl/en_ALL/mapfiles/310c/maps2.api/main.jsSaintebeuve
Shouldn't I just upgrade to V3? Would that solve all of this?Saintebeuve
:( Upgrading to the newer code throws the same error. Error: this.lat is not a function Source File: http://maps.gstatic.com/intl/en_us/mapfiles/api-3/4/9/main.js Line: 11Saintebeuve
Then you got soemthing else going wrong. I posted my initial snippet from working production code.Thiazole
But I need to save it somehow, and that's where the exception is being thrown, on the post. You've shown me how to place a point on a map. I don't have a map here.Saintebeuve
To save it you need to put it in some sort of datastore, DB, cookie, etc.Thiazole
Thanks bud, I figured that :D. But I need to post it to my server in order to save it to my DB, and its throwing the this.lat exception when I try to serialize or post the result.Saintebeuve
That is a different issue altogether and you should post the relevant code for your serialization and posting.Thiazole
I did, in my original question. $.param(point) serializes an object, and I have my post function commented out. Both throw the error.Saintebeuve
P
0

In V3 the coordinates must be first serialized as a string as shown by Arnoldiuss, before sending as json post data.

var lat = latlong.lat().toString().substr(0, 12); var lng = latlong.lng().toString().substr(0, 12);

Pick answered 10/10, 2011 at 16:20 Comment(0)
S
-1
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

<%@ taglib prefix="s" uri="/struts-tags"%>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyDS1d1116agOa2pD9gpCuvRDgqMcCYcNa8&sensor=false"></script>
<script type="text/javascript">
function initialize() {

    var latitude = document.getElementById("latitude").value;
    latitude = latitude.split(",");

    var longitude = document.getElementById("longitude").value;
    longitude = longitude.split(",");

    var locName = document.getElementById("locName").value;
    locName = locName.split(",");

    var RoadPathCoordinates = new Array();
    RoadPathCoordinates.length = locName.length;

    var locations = new Array();
    locations.length = locName.length;

    var infowindow              = new google.maps.InfoWindow();
    var marker, i;
    var myLatLng                = new google.maps.LatLng(22.727622,75.895719);



    var mapOptions = {
        zoom            : 16,
        center          : myLatLng,
        mapTypeId       : google.maps.MapTypeId.ROADMAP
    };
    var map                     = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);


    //To Draw a line
    for (i = 0; i < RoadPathCoordinates.length; i++)
        RoadPathCoordinates[i] = new google.maps.LatLng(latitude[i],longitude[i]);
    var RoadPath = new google.maps.Polyline({
        path            : RoadPathCoordinates,
        strokeColor     : "#FF0000",
        strokeOpacity   : 1.0,
        strokeWeight    : 2
    });


    //Adding Marker to given points
    for (i = 0; i < locations.length; i++)
        locations[i] = [locName[i],latitude[i],longitude[i],i+1];
    for (i = 0; i < locations.length; i++) 
    {marker = new google.maps.Marker({
                position    : new google.maps.LatLng(locations[i][1], locations[i][2]),
                map         : map
                });



    //Adding click event to show Popup Menu
    var LocAddress ="";
    google.maps.event.addListener(marker, 'click', (function(marker, i) 
      { return function() 
        {
            GetAddresss(i);

            //infowindow.setContent(locations[i][0]);

            infowindow.setContent(LocAddress);
            infowindow.open(map, marker);
        }
      })(marker, i));}


 function GetAddresss(MarkerPos){
        var geocoder = null;
        var latlng;
        latlng = new google.maps.LatLng(latitude[MarkerPos],longitude[MarkerPos]);
        LocAddress = "91, BAIKUNTHDHAAM"; //Intializing just to test

        //geocoder = new GClientGeocoder(); //not working
        geocoder = new google.maps.Geocoder();

        geocoder.getLocations(latlng,function ()
        {
            alert(LocAddress);
            if (!response || response.Status.code != 200) {
                alert("Status Code:" + response.Status.code);
            } else 
            {
                place = response.Placemark[0];
                LocAddress = place.address;
            }

        });
 }

    //Setting up path
    RoadPath.setMap(map);   
}
</script>

</head>
<body onload="initialize()">
    <s:form action="mapCls" namespace="/">
        <s:hidden key="latitude" id="latitude"/>
        <s:hidden key="longitude" id="longitude"/>
        <s:hidden key="locName" id="locName"/>
        <div id="map_canvas" style="float:left;width:70%;height:100%"></div>
    </s:form>
</body>
</html>


I am doing reverse Geocoding, and want address of marker using lat and longitude. M facing problem with function "GetAddresss()", line "geocoder.getLocations(latlng,function ()" is not working properly. what should I Do?
Significancy answered 10/8, 2012 at 10:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.