Google Maps GeoCoder Issue - javascript

I'm trying to make a simple page that allows addresses from a mysql database to be converted to lat and long and then displayed as markers on a map.
Most of the code below comes from the google docs with the addition of some geocoder stuff.
I can successfully alert the correct coordinates (see line 48-53) but then I try to pass them into 'point' variable for google maps to create a marker but nothing appears on the map.
Can anyone see whats wrong with my code? I'm not familiar with Javascript so it could be something really fundamentally wrong.
Thanks
function load() {
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 3,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml3.php", function(data) {
var coords;
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
geocoder.geocode( { 'address': address}, function(results, status) {
var latpoint = parseFloat(results[0].geometry.location.lat());
var lngpoint = parseFloat(results[0].geometry.location.lng());
coords = latpoint + ', ' + lngpoint;
//alert(coords); //For Testing
});
var point = new google.maps.LatLng(coords);
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}

The LatLng object constructor is waiting for Number type. Here you give it a string with the concatened coordinates, wich is wrong.
Look at the doc here.
Try that instead :
var latpoint = parseFloat(results[0].geometry.location.lat());
var lngpoint = parseFloat(results[0].geometry.location.lng());
var point = new google.maps.LatLng(latpoint, lngpoint);
And please refer to the #Pekka 웃 comment to be sure people answer you next time.

Related

Using computeDistanceBetween to work out the distance between the user's current location and a fixed point

I'm currently trying to code a simple web-app prototype for one of my university projects. I'm fairly new to Javascript and I'm having some trouble.
I've created a map that drops a marker at the user's current location, and a marker at a fixed point. Here is the Javascript so far:
var map;
function load() {
var myOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
navigator.geolocation.getCurrentPosition(displayOnMap);
}
var pin;
function displayOnMap(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var initialLocation = new google.maps.LatLng(latitude, longitude);
map.setCenter(initialLocation);
var marker = new google.maps.Marker({
map: map,
position: initialLocation,
});
loadMarkers();
}
function loadMarkers() {
var xmlMarkersRequest = new XMLHttpRequest();
xmlMarkersRequest.onreadystatechange = function() {
if (xmlMarkersRequest.readyState === 4) {
var xml = xmlMarkersRequest.responseXML;
var markersArray = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markersArray.length; i++) {
var id = Number(markersArray[i].getAttribute("id"));
var latitude = markersArray[i].getAttribute("latitude");
var longitude = markersArray[i].getAttribute("longitude");
var point = new google.maps.LatLng(
parseFloat(latitude),
parseFloat(longitude));
var marker2 = new google.maps.Marker({
map: map,
position: point,
zIndex: id
});
}
}
}
xmlMarkersRequest.open('GET', 'markers.xml', false);
xmlMarkersRequest.send(null);
}
Everything here works exactly how I want it to.
I'm just not sure how to use computeDistanceBetween to return the distance between the user's initial location (initialLocation), and the location of the marker.
The marker information is stored in an XML file because originally I planned to add more than one. But my site only needs one marker, so it's not a problem if I have to write the fixed marker's information into the Javascript instead.
I hope this question makes sense!
You need to load the geometry library
http://maps.googleapis.com/maps/api/js?key=YOURKEY&libraries=geometry
The distance between two points is the length of the shortest path between them. This shortest path is called a geodesic. On a sphere all geodesics are segments of a great circle. To compute this distance, call computeDistanceBetween() passing it two LatLng objects.
Example:
var a = new google.maps.LatLng(0,0);
var b = new google.maps.LatLng(0,1);
var distance = google.maps.geometry.spherical.computeDistanceBetween(a,b);
distance will be the distance in meters.

Google Maps API missing data from array to markers

Apologies in advance as this may seem a little complicated.
I have a Google Map Marker Array that my markers get added to called markersArray.
The details that get stored per marker are latitude, longitude, title, description.
Using the code below, it runs when a marker is clicked on my map
google.maps.event.addListener(marker, 'click', function(mll) {
console.log(mll);
console.log(markersArray);
var html= "<div style='color:#000;background-color:#fff;padding:5px;width:150px;'><p></p></div>";
iw = new google.maps.InfoWindow({content:html});
iw.open(map,marker);
});
mll shows the log for the actual marker and markersArray just shows me the list of markers within the Array.
What I've noticed is that the data stored in markersArray is no being taken into the actual marker itself.
Is there a way of doing this?
If there isn't is there a way to use Javascript to find the title from the markersArray depending on the latLng values that you will see in the following image.
I screenshot what I receive when I run the Marker Click Function
Markers are added as follows using AngularJS:
$scope.createmarker = function () {
geocoder.geocode({
'address': selectedItem.gps
}, function (response, status) {
geocode_results = new Array();
geocode_results['status'] = status;
top_location = response[0];
var lat = Math.round(top_location.geometry.location.lat() * 1000000) / 1000000;
var lng = Math.round(top_location.geometry.location.lng() * 1000000) / 1000000;
geocode_results['lat'] = lat;
geocode_results['lng'] = lng;
geocode_results['l_type'] = top_location.geometry.location_type;
marker = new google.maps.Marker({
icon: mapIcon,
position: new google.maps.LatLng(lat, lng),
map: map,
title: selectedItem.title
});
markersArray.push(marker);
console.log(markersArray);
console.log(marker);
});
};
Using title instead of mll
google.maps.event.addListener(marker, 'click', function(title) {
console.log(mll);
console.log(markersArray);
var html= "<div style='color:#000;background-color:#fff;padding:5px;width:150px;'><p></p></div>";
iw = new google.maps.InfoWindow({content:html});
iw.open(map,marker);
});

How do I return the City, Street, and Zip Code of a google maps marker?

I have this code that I use to populate two text inputs on a form for Latitude and Longitude. I was wondering if there is a way to retrieve the City, Street, and Zip Code also so I can use those to populate into the form as well?
google.maps.event.addListener(marker, 'dragend', function(marker){
var latLng = marker.latLng;
$latitude.value = latLng.lat();
$longitude.value = latLng.lng();
});
Example:
$zipcode.value = latLng.postal_code();
$street.value = latLng.street_address();
$city.value = latLng.city();
Here is my full code:
function selectState(state_id){
if(state_id!="-1"){
loadData('city',state_id);
var e = document.getElementById("state");
var stateloc = e.options[e.selectedIndex].value;
var address = state_id + stateloc;
var $latitude = document.getElementById('latitude');
var $longitude = document.getElementById('longitude');
var latitude = 73.00636021320537;
var longitude = -23.46687316894531;
var zoom = 10;
geocoder = new google.maps.Geocoder();
var LatLng = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: zoom,
center: LatLng,
panControl: false,
zoomControl: true,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map'),mapOptions);
if (geocoder) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: 'Drag Me!',
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function(marker){
var latLng = marker.latLng;
$latitude.value = latLng.lat();
$longitude.value = latLng.lng();
});
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}else{$("#city_dropdown").html("<option value='-1'>Select city</option>");
}
}
The problem you are facing is solved most simply by making a call to the reverse geocoder, which is at
https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false
A very simple php script could look like this:
<?php
$value=json_decode(file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false"));
echo $value->results[0]->formatted_address;
?>
This produces the output
277 Bedford Avenue, Brooklyn, NY 11211, USA
I suggest (in line with your user name) that you start by "keeping it simple" - strip all the code from your page except the one that takes a Lon/Lat input, and calls the above. Prove to yourself that you can recreate this output (besides the formatted address, there are individual fields for number, street, etc - see the full structure returned). Then add further complexity (maps, pins, pulldowns, ...).
Using the example you had above,
var latitude = 73.00636021320537;
var longitude = -23.46687316894531;
the address returned is
Greenland
I guess that's what happens when you stick a pin in the middle of the wilderness:
UPDATE if you want to do this using only Javascript, you would be well advised to use jQuery to get the JSON parsing capability. Example script (loads same address as original example once page is loaded - the key things are the httpGet function which you could replace with an AJAX call, and the jQuery.parseJSON() call which helps turn the response into something from which you can extract useful information:
<html>
<script src='./js/jquery-1.11.0.min.js'></script>
<script>
function ready()
{
var r = httpGet("https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false");
document.write(getAddress(r));
}
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
function getAddress(response)
{
var obj = jQuery.parseJSON(response);
return obj.results[0].formatted_address;
}
</script>
<body onload="ready()">
</body>
</html>
See this at work at http://www.floris.us/SO/geocode.html

How do I get more results from Google Places / Maps

I am using google maps and I am trying out places API, but something makes me wonder...
If you load maps.google.com and go to Kuala Lumpur, then type "food" in the search-box, you will see hundreds of restaurants on the map. I would like to get these into my own maps.
Using the Places API, I have pretty much copied their example code:
function initialize() {
var plat = 3.15;
var plong = 101.7;
var ppos = new google.maps.LatLng(plat, plong);
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
draggable: false,
zoom: 10,
center: ppos
};
map = new google.maps.Map(document.getElementById("mapcanvas"), mapOptions);
var request = {
location: ppos,
radius: '10000'
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: place.icon
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent("<b>" + place.name + "</b><br/>" + place.vicinity);
infowindow.open(map, this);
});
}
When I execute this code, I do get results, but only very few and only major locations like a few malls and museums. So, How do I get all that beautiful data, that I see on Google's own map?
So it turned out there were a number of problems:
Categorization is broken in Inodesia, so using keyword instead solved the problem, as in:
var request= {
location: ppos,
radius: 10000,
keyword: 'restaurant' }
keyword takes a string rather than an array, and radius takes a number rather than a string. You can see a summary of the types for the request here: http://code.google.com/apis/maps/documentation/javascript/reference.html#PlaceSearchRequest

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

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.
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);
});
}
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.
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);
}
});
});
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);
<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?

Categories

Resources