Draw line between given coordinates using Google Map API [duplicate] - google-maps-api-3

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
polyline snap to road using google maps api v3
My usecase is very common but somehow not finding right solution. I keep recording the coordinates of a moving vehicle and then display the predefined route along with the traveled path. The predefined route and traveled path should be displayed in different color. For displaying predefined path I am using DirectionsService.route. And for traveled path I tried different approaches and none of them worked perfectly.
Draw a Polyline between all the coordinates recorded in path traveled. But in case turn falls between 2 recorded coordinates then the line directly joins the points ignoring the turn.
var line = new google.maps.Polyline({
path: arr_all_coordinates, strokeColor: "red", strokeOpacity: 1, strokeWeight: 1
});
Use new DirectionsRenderer objects to form a route between 2 consecutive coordinates and display with DirectionsService.route till the last coordinate. In this case map keep jumping to the last 2 coordinates and gives focus to the last route drawn. I tried setting preserveViewport to true but didnt work.
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(response);
}
Any suggestion please.

This is basically the same problem as drawing a line that snaps to roads. See my solution for that problem: polyline snap to road using google maps api v3

Related

Google Map API : Marker within marked polygon

I have nearly 4 to 5 thousand markers plotted on the map. I want user to allow to draw a polygon on the map and then delete those markers which are within the shaded polygon. Can anyone please guide me on how to find which markers are within the shaded area of polygon ?
Firstly you'll need to use the geometry library. Append libraries=geometry to the query string of the URL you use for loading the Maps API:
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
Then you can use the containsLocation function to check if each marker is inside the polygon.
for (var i = 0; i < markers.length; i++) {
if (google.maps.geometry.poly.containsLocation(markers[i].getPosition(), yourPolygon)) {
markers[i].setMap(null);
}
}
I'm assuming here you've got these 5k markers in an array called markers. And by 'delete those markers' you simply mean remove them from the view. You'd perhaps also want to fire off an ajax request at this point, and/or remove them from that markers array.

How to draw A LOT of polygons on google maps api v3

I'm trying to create a map that highlights over 2 dozen regions on a google map via coordinates. It seems i'm hitting the query string limit.
Any suggestions as to a work around?
Thanks in advance for all/any recommendations.
Thank you for the comments. I lost track of this post and didn't get a chance to test out your solutions.
The image attached below is what I was trying to fill out.
My polygons are region groupings and i'm trying to color code them.
{
where: "Members in("+arrGrpOne+")",
polygonOptions:{
fillColor: '#FF0000',
fillOpacity : .5
}
},{
where: "Members in ("+arrGrpTwo+")",
polygonOptions:{
fillColor: '#FF00FF',
fillOpacity : .5
}
If i add more where clause i get the following error :
Failed to load resource: the server responded with a status of 400 (Bad Request)
https://mts0.googleapis.com/mapslt/ft?hl=en-US&lyrs=ft%3A115hPQ0BVPioObq47a…vwwtvt,twtuuwvwwtvv&z=12&src=apiv3&xc=1&callback=xdc._d9mcoj&token=25665
Depending on how complex your polygons are you may be able to use encoded polylines:
https://developers.google.com/maps/documentation/staticmaps/?csw=1#EncodedPolylines
Try and recreate your polygon with the interactive encoder.
GitHub should have several libraries available depending on your application.

Google Maps api - drawing library fill polygon before closing shape

I have a google map and I am using the drawing library to let the user draw polygons on the map by clicking to add points.
As a comparison I looked at trulia.com. I don't know how the drawing library setup is being made on trulia (uses backbone and other stuff). While I draw a shape, I want it to get filled as soon as I have 3 points, even if I am still drawing, and the fill should change as I add new points (indicating what the shape/area would be if you'd close it in that moment).
On trulia.com, as soon as you have a 3rd point, the area designated by the existing points gets filled, even though you haven't finished adding points. They're using google maps api, right? But I can't find the setting for something like "fill shape as you add points". I've searched google a lot, no luck.
Does anyone know how to setup the map or the drawing library to have that behavior? I don't think that this behavior can be setup in the polygonOptions (I've looked at all the options documented on developers.google.com)... so, the setting must be somewhere else...
MrCroft, it seems #ddtpoison777 asked a similar question and found the solution among some Google Maps API samples. This is the relevant code taken from the example:
var poly;
var path = new google.maps.MVCArray;
function initialize() {
poly = new google.maps.Polygon({
strokeWeight: 3,
fillColor: '#5555FF'
});
poly.setMap(map);
poly.setPaths(new google.maps.MVCArray([path]));
google.maps.event.addListener(map, 'click', addPoint);
}
function addPoint(event) {
path.insertAt(path.length, event.latLng);
var marker = new google.maps.Marker({
position: event.latLng,
map: map,
draggable: true
});
markers.push(marker);
marker.setTitle("#" + path.length);
}

Dynamically set bounds on nearbySearch based on search critieria

We've implemented a search box and google maps on our page to allow customers to perform searches based on places queries, and so far it's working well. However, using TextSearch we almost always get 20 results (unless it's a specific point). What we prefer though, is to return a set of results that makes more sense to a user based on their search (i.e. if they're searching for churches within a zipcode, we shouldn't show churches outside the zip code).
I know we can bias our results based on location and radius, and even restrict results based on location / radius using NearbySearch.
However, our customers are national users who may be searching in any area in the world, so we're not sure, until the user searches, what location and radius to set as a restriction. I'd like to determine that dynamically based on their query.
For example, in Google Maps if you search for "Churches near 30319" you get a much more localized result set than "Churches near Georgia"
Churches near 30319:
https://maps.google.com/maps?q=churches+near+30319&hl=en&sll=33.772251,-84.296934&sspn=0.049158,0.082312&hq=churches&hnear=Atlanta,+Georgia+30319&t=m&z=14
Churches near Georgia:
https://maps.google.com/maps?q=churches+near+Georgia&hl=en&sll=33.870438,-84.332304&sspn=0.049102,0.082312&hq=churches&hnear=Georgia&t=m&z=8
I've tested doing a separate query using geocode to get the single-point location of the query. i.e.
getGeneralVicinity = ->
address = $('#address').val()
window.oneq.geocode.geocoder.geocode
address: address,
(results, status) ->
if status is google.maps.GeocoderStatus.OK
console.log(results[0].types)
It seems by possibly finding the type of the geocode result (i.e locality) we could determine a radius and use the geometry.location for the location bounds. Unfortunately, it's not consistent, and if a user only searches for "churches", this doesn't give us the desired results.
Any help would be greatly appreciated.
You almost had it. I will refer to the Geocoding API as its JSON feed rather than the Google implementation of it, so detail will come straight from the source. There are some very interesting parameters that come back when geocoding something. Try it:
Georgia: http://maps.googleapis.com/maps/api/geocode/json?address=georgia&sensor=true
30319:http://maps.googleapis.com/maps/api/geocode/json?address=30319&sensor=true
Both of the second-tier address components are Georgia. However, there are a few differing parameters, and the one you want is geometry. This indicates the shape of the area.
Take, for example, the 30319 request. You will get as bounds:
"bounds" : {
"northeast" : {
"lat" : 33.9203610,
"lng" : -84.30943599999999
},
"southwest" : {
"lat" : 33.83286890,
"lng" : -84.35826589999999
}
},
"location" : {
"lat" : 33.87309460,
"lng" : -84.33842899999999
},
This tells you three things:
The corners of the bounding box
The centre of the box (which will be the intersection of the vertex lines)
This allows you to compute the maximum distance from your centre, which you can then feed back into your google places API search as radius. Conversion from lat/long to distance is trivial: it's called the orthodromic path. Two formulas exist - one for small distances (Haversine's formula), the other for large distances (this). Someone wrote a calculator for these: http://williams.best.vwh.net/gccalc.htm . You'll quickly see that the bounding box for 30319 spans 10km, whilst the georgia one spans almost 700 (which would require multiple Google Places requests to match).
Let me know if this wasn't clear and I'll elaborate further.

Geocoding Tweets on a Google Map

Would really appreciate any help with my issue. I've been looking at this terrific tutorial by Marcin Dziewulski who integrated recent tweets and twitter user avatars onto a Google Map. Basically he places the users avatar where they last tweeted. I highly recommend checking the tutorial out here:
http://tympanus.net/codrops/2011/04/13/interactive-google-map/
It all seems to make sense except when it comes down to the actual geocoding of the user. The code works beautifully when the different tweeters are from different cities. However, let's say you wanted to track certain users in one city. They're all geocoded from the center of the city and you can only see one avatar at a time. If you refresh the page, another one will show up, in the exact same spot. This obviously isn't what I want. I assume the problems is in this bit of code:
var users = o.twitter.get(), arr = new Array;
for (i in users){
var user = users[i];
$.getJSON('http://twitter.com/users/show/'+user+'.json?callback=?', function(data) {
var img = data.profile_image_url,
screen_name = data.screen_name;
geocoder.geocode({ address: data.location }, function(response, status){
if (status == google.maps.GeocoderStatus.OK) {
var x = response[0].geometry.location.lat(),
y = response[0].geometry.location.lng();
marker = new google.maps.Marker({
icon: img,
map: map,
title: screen_name,
position: new google.maps.LatLng(x, y)
});
I think something needs to change in the geocoder.geocode({ address: data.location } bit of code, but not 100% positive. I can't seem to find the solution in the Twitter API documentation either.
My question is basically this...can the code above be altered so that it gathers more precise lat and long. coordinates from where tweets are actually generated and then display them correctly at those locations? In other words, don't just put a tweet from NYC in the middle of NYC, but place the avatar at the EXACT location.
I've tested this with my own tweets, with the the location feature of twitter enabled. I just can't figure this out! Thanks again to anyone who can help!
Best,
Brandon
The problem is that the vast majority of tweets are not geocoded but the coords are simply guessed from the user's location settings. If you wanted to display this in an interesting way, consider doing a uniform distribution of "center of city" latlongs. This is what census data map-makers often do when they don't have any more exact positioning data than say a district or a tract.
Unless the tweet was made from a mobile device it's lat/long is going to be where the ISP is registered. If I tweet from my desktop my tweets emanate from the street in front of the capitol here in Nashville. If I use my phone and I allow the twitter app to use my lat/long then that would be different. Trust me, I could instantly use the lat/long data in analysis of twitter streams and I wish it were that simple.
What you could do is add a jitter function that adds random displacement along both the x and y coordinate field to displace the tweets lat/long. Or you could grid it out. If you know how many of them you are getting you can figure out easily the bounding area of your grid and do it like that.

Resources