I am trying to create map markers from an array by using geocoding. I store the addresses on an array as well as the addresses' title. problem is in my loop, the title is being set to the last value of my last array although the markers are being set correctly from the addresses in the array. here is my code:
maprender : function (comp, map) {
new google.maps.Marker({
animation: google.maps.Animation.DROP,
position: new google.maps.LatLng(this._geo.getLatitude(), this._geo.getLongitude()),
map: map
});
var names = new Array("ABC","DEF","GHI"),
mapAdd = new Array();
mapAdd[0] = "Address 1";
mapAdd[1] = "Address 2";
mapAdd[2] = "Address 3";
var geocoder = new google.maps.Geocoder();
for (var i = 0; i < mapAdd.length; i++) {
var lat = 0,
lng = 0,
x = names[i];
geocoder.geocode({
'address': mapAdd[i]},
function (results,status) {
if (status === google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
console.log(lat + " " + lng);
new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
title: x,
map: map
});
console.log(x);
}
}
});
}
}
the title is returning "GHI" on all of the markers.
Based on http://blog.jbrantly.com/2010/04/creating-javascript-function-inside.html
Try it this way
function geocode(i) {
var lat = 0,
lng = 0,
x = names[i];
geocoder.geocode({
'address': mapAdd[i]},
function (results,status) {
if (status === google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
console.log(lat + " " + lng);
new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
title: x,
map: map
});
console.log(x);
}
}
});
}
for (var i = 0; i < mapAdd.length; i++) {
geocode(i);
}
Hope this helps
Related
My code is this but it is failing by the look of it on var markerSpiderfier = new OverlappingMarkerSpiderfier(map, spiderConfig);
$(function(){
$("#geocomplete").geocomplete({
map: ".map_canvas",
details: "form ",
}).bind(
"geocode:result", function(event, result){
var map = $("#geocomplete").geocomplete("map");
var iconBase = "/wp-content/themes/s/icon/";
icon = iconBase + "iconfinder_animal-pet_193_1380308.png"
var features = [];
var hedgehogs;
var feature;
hedgehogs = " <?php echo $map_lng_lat; ?>";
hedgehog_array = hedgehogs.split("&");
var pos = "";
var gm = google.maps;
var spiderConfig = {
keepSpiderfied: true,
event: 'mouseover'
};
var markerSpiderfier = new OverlappingMarkerSpiderfier(map, spiderConfig);
for (index = 0; index < hedgehog_array.length; ++index) {
hedgehog_details_temp = hedgehog_array[index].split("#");
hedgehog_details = hedgehog_details_temp[0].split(",");
hedgehog_title_name = hedgehog_details_temp[1].split("#");
url = "/" + hedgehog_title_name[1];
pos ={ lat: parseFloat(hedgehog_details[0]), lng: parseFloat(hedgehog_details[1])};
tmp = {
'position': pos,
'type': 'hedgehog',
'title': hedgehog_title_name[0],
'url': url
};
features.push(tmp);
markerSpiderfier.addMarker(tmp);
}
var markers = features.map(function(location, i) {
return new google.maps.Marker({
position: features[i].position,
icon: icon,
map: map,
title: features[i].title,
label: features[i].title,
url: features[i].url
});
});
for (index = 0; index < markers.length; ++index) {
google.maps.event.addListener(markers[index], 'click', function() {
window.location.href = this.url;
});
}
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: '/wp-content/themes/s/icon/m'});
var iw = new gm.InfoWindow();
markerSpiderfier.addListener('click', function(marker, e) {
iw.setContent(marker.title);
iw.open(map, marker);
});
markerSpiderfier.addListener('spiderfy', function(markers) {
iw.close();
});
});
document.getElementById("geocomplete").value = "United Kingdom";
$("#geocomplete").trigger("geocode");
$("#find").click(function(){
document.getElementById("geocomplete").value = document.getElementById("search").value + " United Kingdom";
$("#geocomplete").trigger("geocode")
}).click();
});
I'm using gmaps Api to make a route for a person who have to visit a list of markets (my waypoints) to take note of their stocks. I'm using the user's house location for the origin of the route and the location of the markets as my waypoints. The problem is that I don't know which waypoint is the route's destination because I set the property optimization = true when call the the direction service, but the api needs a destination to trace the route.
What I need is a way to tell the api to use the last waypoint of my optimized route as a destination.
You could make multiple requests to the directions service, one with each possible waypoint as the final destination, pick the shortest resulting distance.
proof of concept fiddle
code snippet:
var map;
var directionsServices = [];
var directionsDisplays = [];
// constant "start" address
var start = "Paramus, NJ";
// list of possible candidate destinations/waypoints (must be < 9)
var locations = ["67 E Ridgewood Ave, Paramus, NJ 07652",
"450 Rochelle Ave, Rochelle Park, NJ 07662,",
"720 River Rd, New Milford, NJ 07646",
"280 Main St, New Milford, NJ 07646",
"469 Passaic St, Hackensack, NJ 07601",
"91 Broadway, Elmwood Park, NJ 07407",
"206 Market St, Saddle Brook, NJ 07662"
];
var routes = [];
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
document.getElementById('info').innerHTML += "<u><b>intermediate results:</b></u><br>";
getDirections(start, locations, map);
}
google.maps.event.addDomListener(window, "load", initialize);
function getDirections(start, waypoints, map) {
var requests = [];
var request = {
origin: start,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
for (var j = 0; j < waypoints.length; j++) {
var waypts = [];
for (var i = 0; i < waypoints.length; i++) {
if (i != j) {
waypts.push({
location: waypoints[i],
stopover: true
});
}
}
requests[j] = {};
requests[j].destination = waypoints[j];
requests[j].waypoints = waypts;
requests[j].origin = start;
requests[j].optimizeWaypoints = true;
requests[j].travelMode = google.maps.TravelMode.DRIVING;
setTimeout(function(request, j) {
sendDirectionsRequest(request, j, map);
}(requests[j], j), 3000 * j);
}
}
function sendDirectionsRequest(request, index, map) {
var directionsService = new google.maps.DirectionsService();
directionsServices.push(directionsService);
directionsService.route(request, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
var route = response.routes[0];
routes.push(route);
var distance = 0;
var duration = 0;
for (var i = 0; i < route.legs.length; i++) {
distance += route.legs[i].distance.value;
duration += route.legs[i].duration.value;
}
route.distance = distance;
route.duration = duration;
route.index = index;
document.getElementById('info').innerHTML += (routes.length - 1) + " dist:" + (route.distance / 1000).toFixed(2) + " km dur:" + (route.duration / 60).toFixed(2) + " min dest:" + index + " loc:" + locations[index] + " waypt order:" + route.waypoint_order + "<br>";
if (routes.length == locations.length) {
routes.sort(sortFcn);
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
polylineOptions: {
strokeOpacity: 0.9,
strokeWeight: 4,
strokeColor: "black",
zIndex: 10
}
});
directionsDisplay.setDirections(response);
directionsDisplay.setMap(map);
document.getElementById('info').innerHTML += "<u><b>shortest result:</b></u><br>" + routes[0].index + " dist:" + (routes[0].distance / 1000).toFixed(2) + " km dur:" + (routes[0].duration / 60).toFixed(2) + " min dest:" + routes[0].index + " loc:" + locations[index] + " waypt order:" + routes[0].waypoint_order + "<br>";
}
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
function sortFcn(a, b) {
if (a.distance > b.distance) return 1;
else if (a.distance < b.distance) return -1;
else return 0;
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="info"></div>
<div id="map_canvas"></div>
As I am new to KineticJs so, I have tried implementing the functionality using Kinectic js for drawing the multiple image on different- different x and y. Now I wanted to resize the stage layer or canvas. I have done that by using the code given below
window.onresize = function (event) {
stage.setWidth(($('#tab' + tabId).innerWidth() / 100) * 80);
var _images = layer.getChildren();
for (var i = 0; i < _images.length; i++) {
if (typeof _images[i].getId() != 'undefined') {
//alert(stage.getScale().x);
_images[i].setX(_images[i].getX() * stage.getScale().x);
layer.draw();
}
}
}
but now the problem is the are being defined and now if browser resize than stage is resized but the images on the prev x and y are fixed . I would like to keep them fixed on the position on resizing of stage layer or canvas.Here are the link of the image before resize and after resizing.beforeresize and afterResize .
Here is my entire code given below:-
$("#tabs li").each(function () {
$(this).live("click", function () {
clearInterval(_timer);
var tabname = $(this).find("a").attr('name');
tabname = $.trim(tabname.replace("#tab", ""));
var tabId = $(this).find("a").attr('href');
tabId = $.trim(tabId.replace("#", ""));
$.ajax({
url: "/Home/GetTabsDetail",
dataType: 'json',
type: 'GET',
data: { tabId: tabId },
cache: false,
success: function (data) {
var bayStatus = [];
var i = 0;
var image_array = [];
var BayExist = false;
var BayCondition;
var imgSrc;
var CanvasBacgroundImage;
var _X;
var _bayNumber;
var _Y;
var _ZoneName;
$(data).each(function (i, val) {
i = i + 1;
if (!BayExist) {
bayStatus = val.BayStatus;
CanvasBacgroundImage = val.TabImageLocation;
BayExist = true;
}
$.each(val, function (k, v) {
if (k == "BayNumber") {
BayCondition = bayStatus[v];
_bayNumber = v;
if (BayCondition == "O")
imgSrc = "../../images/Parking/OccupiedCar.gif"
else if (BayCondition == "N")
imgSrc = "../../images/Parking/OpenCar.gif";
}
if (k == "BayX")
_X = v;
if (k == "BayY")
_Y = v;
if (k == "ZoneName")
_ZoneName = v;
});
image_array.push({ img: imgSrc, xAxis: _X, yAxis: _Y, toolTip: _bayNumber, ZoneName: _ZoneName });
});
var imageUrl = CanvasBacgroundImage;
if ($('#tab' + tabId).length) {
// $('#tab' + tabId).css('background-image', 'url("../../images/Parking/' + imageUrl + '")');
var stage = new Kinetic.Stage({
container: 'tab' + tabId,
width: ($('#tab' + tabId).innerWidth() / 100) * 80, // 80% width of the window.
height: 308
});
window.onresize = function (event) {
stage.setWidth(($('#tab' + tabId).innerWidth() / 100) * 80);
}
$('#tab' + tabId).find('.kineticjs-content').css({ 'background-image': 'url("../../images/Parking/' + imageUrl + '")', 'background-repeat': ' no-repeat', 'background-size': '100% 100%' });
var layer = new Kinetic.Layer();
var planetOverlay;
function writeMessage(message, _x, _y) {
text.setX(_x + 20);
text.setY(_y + 1);
text.setText(message);
layer.draw();
}
var text = new Kinetic.Text({
fontFamily: 'Arial',
fontSize: 14,
text: '',
fill: '#000',
width: 200,
height: 60,
align: 'center'
});
var opentooltip = new Opentip(
"div#tab" + tabId, //target element
"dummy", // will be replaced
"", // title
{
showOn: null // I'll manually manage the showOn effect
});
Opentip.styles.win = {
borderColor: "black",
shadow: false,
background: "#EAEAEA"
};
Opentip.defaultStyle = "win";
// _timer = setInterval(function () {
for (i = 0; i < image_array.length; i++) {
img = new Image();
img.src = image_array[i].img;
planetOverlay = new Kinetic.Image({
x: image_array[i].xAxis,
y: image_array[i].yAxis,
image: img,
height: 18,
width: 18,
id: image_array[i].toolTip,
name: image_array[i].ZoneName
});
planetOverlay.on('mouseover', function () {
opentooltip.setContent("<span style='color:#87898C;'><b>Bay:</b></span> <span style='color:#25A0D3;'>" + this.getId() + "</span><br> <span style='color:#87898C;'><b>Zone:</b></span><span style='color:#25A0D3;'>" + this.getName() + "</span>");
//writeMessage("Bay: " + this.getId() + " , Zone: " + this.getName(), this.getX(), this.getY());//other way of showing tooltip
opentooltip.show();
$("#opentip-1").offset({ left: this.getX(), top: this.getY() });
});
planetOverlay.on('mouseout', function () {
opentooltip.hide();
// writeMessage('');
});
planetOverlay.createImageHitRegion(function () {
layer.draw();
});
layer.add(planetOverlay);
layer.add(text);
stage.add(layer);
}
// clearInterval(_timer);
//$("#tab3 .kineticjs-content").find("canvas").css('background-image', 'url("' + imageUrl + '")');
// },
// 500)
}
}
,
error: function (result) {
alert('error');
}
});
});
});
I want to keep the icons on the position where they were before resizing. I have tried but could not get the right solution to get this done.
How can How can I update x,y position for the images . Any suggestions would be appreciated.
Thanks is advance.
In window.resize, you're changing the stage width by a scaling factor.
Save that scaling factor.
Then multiply the 'x' coordinate of your images by that scaling factor.
You can reset the 'x' position of your image like this:
yourImage.setX( yourImage.getX() * scalingFactor );
layer.draw();
In the above mentioned code for window.onresize. The code has been modified which as follow:-
window.onresize = function (event) {
_orignalWidth = stage.getWidth();
var _orignalHeight = stage.getHeight();
// alert(_orignalWidth);
// alert($('#tab' + tabId).outerHeight());
stage.setWidth(($('#tab' + tabId).innerWidth() / 100) * 80);
//stage.setHeight(($('#tab' + tabId).outerHeight() / 100) * 80);
_resizedWidth = stage.getWidth();
_resizedHeight = stage.getHeight();
// alert(_resizedWidth);
_scaleFactorX = _resizedWidth / _orignalWidth;
var _scaleFactorY = _resizedHeight / _orignalHeight;
//alert(_scaleFactor);
var _images = layer.getChildren();
for (var i = 0; i < _images.length; i++) {
if (typeof _images[i].getId() != 'undefined') {
//alert(stage.getScale().x);
_images[i].setX(_images[i].getX() * _scaleFactorX);
//_images[i].setY(_images[i].getY() * _scaleFactorY);
layer.draw();
}
}
}
i am new to programming.. i have this code which gives distance between two points but need to further multiply it by an integer say 10.. the project i am working on is abt calculating distance between two points and multiplying it with fare/Km like Rs.10/km (Indian Rupees) for the same. So if the distance is 30 km the fare would be 30*10 = Rs.300
Thanks in advance
following is the code
<script>
var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var origin1 = '';
var destinationA = '';
var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';
function initialize() {
var opts = {
center: new google.maps.LatLng(55.53, 9.4),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), opts);
var fromText = document.getElementById('FAdd');
var options = {
componentRestrictions: {country: 'in'}
};var fromAuto = new google.maps.places.Autocomplete(fromText, options);
fromAuto.bindTo('bound', map);
var toText = document.getElementById('TAdd');
var toAuto = new google.maps.places.Autocomplete(toText, options);
toAuto.bindTo('bound', map);
geocoder = new google.maps.Geocoder();
}
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [document.getElementById("FAdd").value],
destinations: [document.getElementById("TAdd").value],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
outputDiv.innerHTML = '';
deleteOverlays();
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
addMarker(destinations[j], true);
outputDiv.innerHTML += results[j].distance.text + '<br>';
}
}
}
}
function addMarker(location, isDestination) {
var icon;
if (isDestination) {
icon = destinationIcon;
} else {
icon = originIcon;
}
geocoder.geocode({'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: icon
});
markersArray.push(marker);
} else {
alert('Geocode was not successful for the following reason: '
+ status);
}
});
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
I use an Ajax call to PHP, and haven't yet used getDistanceMatrix(), but this should be an easy fix.
First, if you know you will always only have one origin and one destination, you don't need the "for" loop in your callback function. Second, you're taking the distance text rather than the distance value.
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
[...]
} else {
deleteOverlays();
var outputDiv = document.getElementById('outputDiv'),
origin = response.originAddresses[0],
destination = response.destinationAddresses[0],
result = response.rows[0].elements[0],
distance = result.distance.value,
text = result.distance.text,
price = 10 * distance;
outputDiv.innerHTML = '<p>' + text + ': Rs.' + price + '</p>';
addMarker(origin, false);
addMarker(destination, false);
}
}
I haven't tested this, so it probably needs to be tweaked. ( See https://developers.google.com/maps/documentation/distancematrix/#DistanceMatrixResponses )
I am using the blowing script to get all store around position wit 20 mile and working well but when try to using it to get postal_code do not working
how i get all postal code around center with specific distance
code:
<script type="text/javascript" language="javascript">
var lat = "";
var lng = "";
function latClick(glocation) {
var a = new google.maps.Geocoder();
a.geocode({ 'address': glocation }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK)
var c = results;
else
c = "We couldn't find that location. Please try again."
lat = c[0].geometry.location.lat();
lng = c[0].geometry.location.lng();
var pyrmont = new google.maps.LatLng(lat, lng);
//sll=30.04443,31.234217&sspn=0.036703,0.084543&geocode=FU1wygEdO5jcAQ%3BFQRxygEdgJ7cASnrviELpj9YFDG6O0LolrLfeQ&mra=mift&
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: 200,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
});
}
var map;
var infowindow;
function initialize() {
latClick("Jersey City, NJ 07306, United States");
}
function callback(results, status) {
var x = "";
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
x = x + results[i].name + ", ";
}
alert(x);
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>