Convert zip code to latitude/longitude coordinates using Google Maps API? - javascript

I've been looking through the docs and all over the web for an example of this and I can't find an example of this use-case.
Given a zip code, I need a rough approximation of the user's location in the form of lat/long coordinates. All I have is the zip code, nothing else.
Can this be done using Google Maps API? If not, what other resources would you suggest looking at?

You can pass any text as the address key for the geocoder. If the geocoding is successsful, you should get an array of results.
From then on you can pick the first result or iterate over the array. Each of its elements should contain an address object, and postal code is one posible field on that obj.
Keep in mind that usps zipcodes are not points nor shapes. They are arrays of points, and the centroid of the polygon drawn by using those points as vertexes probably doesn't have any special meaning.

maybe you can do this by php with the following script:
function getLnt($zip){
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($zip)."&sensor=false";
$result_string = file_get_contents($url);
$result = json_decode($result_string, true);
$result1[]=$result['results'][0];
$result2[]=$result1[0]['geometry'];
$result3[]=$result2[0]['location'];
return $result3[0];
}
if you call this function by (* I filtered out the space between chars, it isn't necessary):
$coords = str_replace(' ','',$foo->zipcode);*
$val = getLnt($coords);
/* print latitude & longitude for example */
print $val['lat'];
print $val['lng'];
Then after that u can mix it with your google map script like:
function initialize(){
var myLatlng = new google.maps.LatLng(<?= $val['lat'] ?>,<?= $val['lng'] ?>);
var mapOptions = {
zoom: 14,
center: myLatlng,
disableDefaultUI: true,
scrollwheel: false,
}
var map = new google.maps.Map(document.getElementById('propMap'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'title of location',
icon: iconBase + 'google-marker.png'
});
}
Note: This worked fine for me, but maybe there are better ways to do this ;-)

Related

event.latLng returns latitude and longitude, however, I can't extract just lat or lng [duplicate]

I have an old gmaps application using V2 and I am trying to update it to v3.
I have a really simple problem, but I can't find a solution yet.
How can I strip the latitude and the longitude from the "event.latLng"?
It is returning a point(), but I need only the lat alone and the long for itself.
I cant get this to work.
According to the API for MouseEvents, event.latLng contains a LatLng, not a Point. If this is the case then you can use the lat() and lng() methods to get the values separately. If event.latLng is actually a Point then you can directly access the coordinates using the x and y properties (not methods).
What type of listener is creating the event?
Edit: there's an example in the tutorial of how to do what you want. It looks like you're following this already. Did you remember to include the actual placeMarker() function declaration?
function placeMarker(location) {
var clickedLocation = new google.maps.LatLng(location);
var marker = new google.maps.Marker({
position: location,
map: map
});
map.setCenter(location);
}
Or are you not interested in placing a marker, and just want to get the lat and lng values? In that case, all you need is:
google.maps.event.addListener(map, 'click', function(event) {
var myLatLng = event.latLng;
var lat = myLatLng.lat();
var lng = myLatLng.lng();
})

Capturing latitude and longitude on marker drag in MapQuest

I can't seem to find a way to get the latitude and longitude from existing markers in MapQuest.
I currently set my directions map using:
var map = L.mapquest.map('map', {
center: [selfLatitude, selfLongitude],
layers: L.mapquest.tileLayer('map'),
zoom: 13
});
L.mapquest.directions().route({
start: [selfLatitude, selfLongitude],
end: [otherLatitude, otherLongitude]
});
This produces a Map with the two points and the direction between them.
I am able to move the end point on the map but want to capture the modified latitude and longitude.
What is the proper way to target and get the coordinates from individual markers in a MapQuest Map using the mapquest.js javascript library?
I thought this would be an easy solution, but I could not find anything easily in their documentation. I tried picking apart their examples and looking everywhere for bit of information. After assuming this would work, but didn't because getLatLng() is not a function:
popup.on('dragend', function(event) {
var marker = event.target;
var position = marker.getLatLng().wrap();
showLL(position, 'USER_DEFINED');
});
At some point I decided to stop looking at the doc's they provided and tried to look at their Lat/Long finder example and look further into the event.target object that was returned and tried to find anything related to the lat and long.
I know you asked for a "proper" way, but I honestly couldn't find one and thought I should share anyways.
The below is def not an official way to do this, but I believe it works. For some reason the moveend event is fired whether the start or end is moved, but I only log the end lat/long anyways.
I noticed that marker._layers[prop].locationIndex was mixed in the layers obj and 0 seems to correlate to the start marker and 1 seemed to point to the end marker.
Here's what I came up with:
let latLng1 = new L.LatLng(35.6009, -82.554);
let latLng2 = new L.LatLng(35.7796, -78.6382);
let map = L.mapquest.map('map', {
center: latLng1,
layers: L.mapquest.tileLayer('map'),
zoom: 13
});
let directions = L.mapquest.directions();
directions.route({
start: latLng1,
end: latLng2
});
map.on('moveend', function(event) {
let marker = event.target;
for (let prop in marker._layers) {
if (!marker._layers.hasOwnProperty(prop)) continue;
// locationIndex- I am assuming 0 for start marker and 1 for end marker.
if (marker._layers[prop].locationIndex === 1) {
let latLong = marker._layers[prop]._latlng;
console.log(latLong)
}
}
});
}

Get coordinates, measure distances, and compare them

It was proposed to develop a page where you present an excerpt of Google Maps with several markers organized in clusters (done). I do not have experience with javascript, and what I need is that clicking a button or not, it is possible to get my location and automatically be informed of which point marked on the map is closer to me. Can someone help me?
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: {lat: 40.963308, lng: -8.594651}
});
// Create an array of alphabetical characters used to label the markers.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
var locations = [
{lat: 40.962157, lng: -8.593313},
{lat: 40.962149, lng: -8.595695},
{lat: 40.960351, lng: -8.598922},
{lat: 40.967305, lng: -8.591450},
{lat: 40.961682, lng: -8.608136}
]
</script>
If you are talking about the aerial distance, use the Euclidean formula on all, pretty fast, considering everything. Just modify it a little, so you don't use the square root, as it is an expensive operation.
(Xpos - Xpoint)^2 + (Ypos - Ypoint)^2
Apply a basic min alogirthm, i.e. always save the lowest distance point.
That's the easy way, generally also the nearest point, if taking places far away.
The way to do the road distance previously would have been to do it one by one, but Google thankfully thought of this case and developed https://developers.google.com/maps/documentation/distance-matrix/intro
I am not sure what the usage quota for your account will be, but that's upto you and your company to figure out depending on the type of plan you want.

Google Maps v3 - Limit area where a function can work

In my javascript code using Google Maps API v3 I tried to set bounds to the Autocomplete function, it works quite well infact as soon as I type a letter in the input field (html), the same autocomplete advise me with addresses that can be found in the bounds area, however if I type the name of a city that is outside bounds limit I get advice also for that and other cities. Is there a way to avoid this? I'd like to have only advice for my "bounds".
Here is the piece of code:
init = function() {
var latlng = new google.maps.LatLng(40.635636, 17.942414);
var mapOptions = { zoom: 13, center: latlng, minZoom: 10, maxZoom: 16};
default_bounds = new google.maps.LatLngBounds();
default_bounds.extend(new google.maps.LatLng(40.635636-0.33, 17.942414-0.33));
default_bounds.extend(new google.maps.LatLng(40.635636+0.33, 17.942414+0.33));
console.log("Initialing map at: 40.635636, 17.942414");
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
originAutocomplete = new google.maps.places.Autocomplete(document.getElementsByName("origin")[0], {types: ['geocode']});
destinationAutocomplete = new google.maps.places.Autocomplete(document.getElementsByName("destination")[0], {types: ['geocode']});
originAutocomplete.setBounds(default_bounds);
destinationAutocomplete.setBounds(default_bounds);
}
Correct image: (show only places in Puglia south Italy)
Incorrect image: (show places of many different regions)
According to the documentation, there are 4 ways to set biases and search-area boundaries for Autocomplete, and they are
* Set the bounds on creation of the Autocomplete object.
* Change the bounds on an existing Autocomplete.
* Set the bounds to the map's viewport.
* Restrict the search to a specific country.
Since the first 3 options would only bias, but not restrict the result, you can only filter out other country's information, but not cities from the same country.
Note that you might able to modify the result by playing with the return object, but that is a violation of the ToS.

Get N Markers that are closest to the center in Google Maps

I'm trying to figure out how to sort the first 10 Markers on a Google map by distance from the center of the map in Javascript. So, let's say I have 100 Markers in an array, and I want to display more information about the first 10 closest markers in a HTML unordered list. How would I go about doing that?
I found a similar example for Google Maps API version 2 here, but nothing for version 3.
Whatever happens You need to calculate all distances. You can do it yourself with simple equations or use Google's geometry library: http://code.google.com/intl/pl-PL/apis/maps/documentation/javascript/geometry.html and its function: computeDistanceBetween(). Then store distance in custom marker property like e.g:
marker.distance = google.maps.geometry.spherical.computeDistanceBetween(marker.position, center.position);
and sort it anyway you want.
Hope it helps.
Sort the array by proximity to your map's centre point. Use sort().
Slice the first 10 with slice().
Plot these on the map.
There are a few questions like this on StackOverflow but none of them really show a complete example that is easy to read and understand, so I put one together. This is using the lodash/underscore sortBy function for the sorting.
const map = new google.maps.Map('#map', { center: { lat: 47.6541773, lng: -122.3500004 } });
const markers = [
new google.maps.Marker({ position: { lat: 47.6485476, lng: -122.3471675 }, map }),
new google.maps.Marker({ position: { lat: 47.6606304, lng: -122.3651889 }, map })
// ...
];
const sortedMarkers = _.sortBy(markers, marker => {
google.maps.geometry.spherical.computeDistanceBetween(
marker.position,
map.getCenter()
)
});
const firstTenSortedMarkers = sortedMarkers.slice(10);
The sortBy function iterates through each marker in the array and sorts the list based on the value returned by the function that is it's second argument. The computeDistanceBetween function returns a number representing the distance in meters between the map center and the marker position, which is easy to sort on.

Categories

Resources