Google Maps v3 - Limit area where a function can work - javascript

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.

Related

Creating a food places/restaurant Autocomplete field with multiple bounds using Google Maps JavaScript API

I am attempting to create a food places/restaurants Autocomplete field that does the following:
Prioritizes so food places/restaurants near both Office 1 and Office 2 (Latitude/Longitude) display first. (It seems like when you pass multiple LatLng combinations as the bounds it does not do this. Would like to confirm it is not possible.)
Shows only places that are food related. (I believe with Autocomplete this is not possible because it is restricted to passing in only certain place types)
Here is the closest I could get to what I am trying to achieve. However it only works correctly if I pass in a single LatLng for either Office 1 or Office 2, but not both.
<script type="text/javascript">
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-60.8474, 200.2631));
var input = document.getElementById('searchTextField');
var options = {
bounds: defaultBounds,
types: ['establishment']
};
autocomplete = new google.maps.places.Autocomplete(input, options);
</script>
The LatLngBounds takes a south-west co-ordinate as its first argument, and a north-east as a second. In your example, your second co-ordinate is more southern than the first and so the bounds are invalid:
This alternative ought to work regardless of relative position of the points:
var defaultBounds = new google.maps.LatLngBounds(new google.maps.LatLng(-33.8902, 151.1759));
defaultBounds.extend(new google.maps.LatLng(-60.8474, 200.2631));

how to make the map clusters larger distance in less dense area in map instead of showing markers

I am using google map(clustering version) from the following link:
google map clusterer
everything is good and for example when I have 1000 location it clusters them but when I have 200 location and density is not high it does not clusters. I want to clusters even those that are not dense what should I do? is there anyway that I can change level of sensitivity of this google map to distance and zoom to be able to cluster even markers in a less dense area?
As you figured out which parameters to use with the above comments, here is how to pass these params to your marker cluster constructor:
var mcOptions = {
gridSize: 50,
minimumClusterSize: 10
};
var markerCluster = new MarkerClusterer(map, markers, mcOptions);
Where map is your map object and markers is your markers array. The numbers used are only for example. You have to play with these to get the desired results. Hope this helps.
Swift
cluster size change worked for me this way in the latest version and its super easy
// Set up the cluster manager with the supplied icon generator and
// renderer.
let iconGenerator = GMUDefaultClusterIconGenerator()
let algorithm = GMUNonHierarchicalDistanceBasedAlgorithm()
let renderer = GMUDefaultClusterRenderer(mapView: mapView,
clusterIconGenerator: iconGenerator)
renderer.delegate = self
renderer.minimumClusterSize = 5 // Here is the setting
clusterManager = GMUClusterManager(map: mapView, algorithm: algorithm,
renderer: renderer)
clusterManager.setDelegate(self, mapDelegate: self)

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

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 ;-)

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.

Openlayers - Projection issues when getting latitude/longitude from a point

I'm trying to get the latitude/longitude from a draggable marker with Openlayers and OSM but I can't find the good settings for the projection conversion, what I am doing wrong ?
Here is the code: http://pastie.org/2300321 (see addMarker l140 & updateTargets l153) & and a little demo test.
If you submit an address, then drag the marker, the longitude and latitude are wrong. I tested a few different projections but I'm not sure what I've to useā€¦
I think the problem is inside updateTargets method:
var point = this.feature.geometry;
var pixel = new OpenLayers.Pixel(point.x, point.y);
var coord = this.map.getLonLatFromPixel(pixel).transform(
new OpenLayers.Projection("EPSG:900913"),
new OpenLayers.Projection("EPSG:4326")
);
this.feature.geometry is already specified in lon/lat coordinates, not in pixels. So I suggest that you skip second line and do the conversion from OpenStreetMap projection to lon/lat directly on geometry object:
var coord = this.feature.geometry.transform(
new OpenLayers.Projection("EPSG:900913"),
new OpenLayers.Projection("EPSG:4326")
);

Categories

Resources