Rectangle 27 1

The types are available on the Google Places API /Autocomplete response on the "types" array:

{
                  "description" : "Italy", "id" : "25e96cea79a01f7308e93c44a0df106bb0f95e3f", 
                  "matched_substrings" : [ { "length" : 2, "offset" : 0 } ],
                  "place_id" : "ChIJA9KNRIL-1BIRb15jJFz1LOI",
                  "reference" : "CiQdAAAA70Hqa7YV7SeclW_Lfg1TB2s1o5aAk9j9iRn79CODJI4SEFgu3rYiXss6oQY1PKBniy8aFN5525fCHdYaSHfFcuK1jmf4tGiv",
                  "terms" : [ { "offset" : 0, "value" : "Italy" } ],
                  "types" : [ "country", "political", "geocode" ] 
                }
{ "description" : "Itingen, Switzerland", "id" : "d3caa11828d35eb13c066fa987a5859cf4dc8219", "matched_substrings" : [ { "length" : 2, "offset" : 0 } ], "place_id" : "ChIJo5eKUs7KkUcRdgR0wD1DONE", "reference" : "CjQsAAAAur4OIssVGpNZ68mQn4zwvkFWl2vqGEdJYpO1BVc9aUU8XtJ7uQyen-tPXaDGxf-3EhANsxjvPxzsAAGVyBzP0LPeGhREmHdg7PVMtfsodwFN0KO4z6hqDA", "terms" : [ { "offset" : 0, "value" : "Itingen" }, { "offset" : 9, "value" : "Switzerland" } ], "types" : [ "locality", "political", "geocode" ] }

php - How to get the location type or how to identify if a given locat...

php google-maps-api-3 google-places-api google-geocoding-api google-places
Rectangle 27 0

function get_cities($Country){
  $this->load->model('city_model');
  header('Content-Type: application/x-json; charset=utf-8');
  echo(json_encode($this->cities_model->get_cities($dealCountry)));
}

php - Ajax drop down for Country State & City in Codeigniter? - Stack ...

php codeigniter drop-down-menu
Rectangle 27 0

As I have said in the comments, you can use Firebug or Chrome dev tools(network tab) to identify your problem:

<?php
class ctrl extends ci_controller{
    function index(){ //I just used this one to test out if its outputing anything
        $names = ['apple','ball','cat','dog'];
        echo json_encode($names);
    }

    function load_view(){ 
        $this->load->view('ctrl_view');
    }
}
?>
<script src="/tester/ci/js/jquery172.js"></script>
<input type="text" list="names" id="name" autocomplete="off"/>
<datalist id="names">
</datalist>

<script>
$.post('ctrl/', function(data){ //you can just call out your controller here
    var parsed_data = JSON.parse(data);

    //its a good practice to use a document fragment to append new elements to and not append a    new element on every iteration of the loop in an existing element in the dom
    var fragment = document.createDocumentFragment();

    for(var x in parsed_data){
        var val = parsed_data[x];
        var option = $("<option>").val(val).text(val);
        fragment.appendChild(option[0]); 
    }

    $('#names').append(fragment); //append the whole fragment outside the loop
});
</script>

I don't really know what your actual problem is so do us a favor, edit your question and paste what error you see on firebug.

php - Ajax drop down for Country State & City in Codeigniter? - Stack ...

php codeigniter drop-down-menu
Rectangle 27 0

This is a very old project so I did it through Javascript and not jQuery; I hope this is okay.

<td>Type</td>
<td>
      <select  id="type" onChange="propertyType(this.value)" name="type">
                            <option value="">All</option>
                            <option value="homes">Homes</option>
                            <option value="plots">Plots</option>
                            <option value="commercial">Commercial</option>
      </select>
</td>
function propertyType(str){
  if(str=='' || str=='plots'){
    document.getElementById("type_h").innerHTML=""; 
    document.getElementById("bed").innerHTML="";    
    }   
    else if(str=='commercial'){
    document.getElementById("bed").innerHTML="";    
          }
 else{
  document.getElementById("type_h").innerHTML="<img src='<?php echo $serverimageurl?>ajax-loader-small.gif' />";
    if(window.XMLHttpRequest){
    xmlhttp=new XMLHttpRequest();
 }
 else
{
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
    xmlhttp.onreadystatechange=function()
   {
    if(xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById("type_h").innerHTML=xmlhttp.responseText;
    }
   }
   xmlhttp.open("GET","ajax/propertytype.php?s="+str,true);
   xmlhttp.send();
   }
 }
<?php
  $s=$_GET["s"];
  if($s=="homes"){
   ?>


 <select onchange="ajax_bed(this.value)" name="subtype" id="subtype" >
  <option value="">Type Of Houses</option>
  <option value="houses">Houses</option>
  <option value="flats">Flats</option>
  <option value="farmhouses">Farm Houses</option>
</select>

<?php
}
 if($s=="plots")
{
?>


 <?php
  }
  if($s=="commercial")
  {
  ?>
  <select name="subtype" id="subtype" >
   <option value="offices">Offices</option>
   <option value="shops">Shops</option>
   <option value="warehouses">Warehouses</option>
   <option value="factories">Factories</option>
   <option value="building">Buildings</option>
   <option value="other">Other</option>
  </select>
   <?php
  }
?>

This is ajax function for selecting the number of bed rooms

function ajax_bed(str){
  document.getElementById("bed").innerHTML="<img src='<?php echo $serverimageurl?>ajax-loader-small.gif' />";
  if(window.XMLHttpRequest){
    xmlhttp=new XMLHttpRequest();
   }
  else
    {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
    xmlhttp.onreadystatechange=function()
   {
    if(xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        document.getElementById("bed").innerHTML=xmlhttp.responseText;
    }
   }
   xmlhttp.open("GET","ajax/bedroomsselection.php?t="+str,true);
   xmlhttp.send();
 }
<?php
$t=$_GET["t"];
if($t=="houses"||$t=="flats"||$t=="farmhouses")
{
?>
 <select id="bed" name="bed">
   <option>None</option>
   <option>Single Bed</option>
   <option>Double Bed</option>
   <option>three Bed</option>
   <option>Four Bed</option>
   <option>Five Bed</option>
   <option>Six Bed</option>
   <option>Seven Bed</option>
   <option>Eight Bed</option>
   <option>Ten Bed</option>
   <option>More Than Ten Bed</option>
</select>


 <?php
 }
?>

php - ajax dropdown(country, state, city) - Stack Overflow

php ajax
Rectangle 27 0

print a drop down with state list make the list id of state get or post id by methods, make a sql city list table and use php to make call the table it take more time then jquery but it work

php - Country/City/state validation - Stack Overflow

php jquery validation geocode
Rectangle 27 0

1) create 3 tables in db

country table
==============
countryId || countryName

stateTable
=============
stateId || stateName || countryName

city table
=============
cityId || cityName || stateId

3) now on html page create three select box and bind onchange event on each select box (except for city select), that event will send countryId for getStates Webservcie and stateId for getCities webservice. and bind received json states in state select box and cities in city select box

hey this i know, but i dont know the ajax function methods for this

php - ajax dropdown(country, state, city) - Stack Overflow

php ajax
Rectangle 27 0

Visit this page for using tree view structure in jq UI

You can use This by using AJAX

jquery - Display Country, State, City, Area dynamically in tree view u...

php jquery codeigniter
Rectangle 27 0

This is tricky because by default google places will look up locations nearby the center of the map, regardless the suggestions in the dropdown.

So you must find the first suggestion from the dropdown, document.querySelector('.pac-item') - extract the location and use geocoder to lookup the latlng for that location.

Code for extracting the location :

function extractLocation(item) {
    var text = item.innerText || item.textContent;
    var upper = text.toUpperCase();
    var result='';
    for (var i=0;i<text.length;i++) {
        if (text[i]==upper[i]) {
            result+=' ';
        }
        result+=text[i];
    }
    return result;
}

On searchbox enter, select the first suggestion, extract the location, lookup latlng by geocoder and place marker :

input.onkeyup = function(e) {
   var code = (e.keyCode ? e.keyCode : e.which);
   var places = searchBox.getPlaces();
   if (code == 13 && places!=[]) {
     var firstSuggestion = document.querySelector('.pac-item');
     var query = extractLocation(firstSuggestion);
     geocoder.geocode({"address":query }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          clearMarkers();   
          var latLng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
          var marker = new google.maps.Marker({
             map: map,
             title: results[0].address_components[0].long_name,
             position: latLng,
          });
          markers.push(marker);
          map.setCenter(latLng);
          map.setZoom(10);
       }
     });
   } 
}

javascript - how to auto fill state and country by name of city in goo...

javascript php jquery google-maps google-maps-api-3
Rectangle 27 0

Yes, Google wrote some good stuff on this subject, particularly maintaining ajax application state with fragment identifiers: http://code.google.com/web/ajaxcrawling/docs/specification.html

// Special handler for ajax partials ("AHAH" paradigm)
if (isset($_GET['_escaped_fragment']))
{
    // Grab just the fragment
    $fragment = $_GET['_escaped_fragment'];

    // See if we have GET parameters to extract from the fragment
    if (FALSE !== ($p = strpos($fragment, '?')))
    {
        // Make sure to save additional GET parameters
        $additional_params = array_diff_key($_GET, array('_escaped_fragment' => 1));

        // Parse the querty string
        parse_str(substr($fragment, $p+1), $_GET);

        // Add the originals back in
        $_GET = array_merge($_GET, $additional_params);

        // The beginning part of the fragment is the base URI
        $fragment = substr($fragment, 0, $p);
    }

    // Otherwise, clear the $_GET array
    else
    {
        $_GET = array();
    }

    $_SERVER['PATH_INFO']   = $fragment;
    $_SERVER['REQUEST_URI'] = $fragment;

    // Add a constant for use throughout the app
    define('IS_FRAGMENT', 1);
}
defined('IS_FRAGMENT') OR define('IS_FRAGMENT', 0);

1) If it's an ajax request and IS_FRAGMENT == 1, then display just the partial results you need to populate your front-end changes

2) Otherwise, assume it's either a search engine or a direct page load. Display the fully built page.

You shouldn't necessarily created separate endpoints just for the ajax requests. It's probably better to extend the Output class to provide a response in the requested format. It's more RESTful that way.

It's also good practice to leverage the HTML5 History API for browsers that can handle it, and fall back to the onhashchange event for the others.

Use "#!" to indicate ajax-triggered content changes, rather than just a "#". You might at some point want to use the default anchor functionality that the fragment provides (but the exclamation point is "safe" as you probably won't have element IDs starting with that particular character).

I would also recommend using an absolute URI (i.e. #!/USA/NY/Albany), as it will be easier to stay consistent in your ajax partial loading mechanism.

Additionally, if someone reloads the page with the ajaxed-fragment in the URL, it can get pretty messy if you don't just do a window.location.href = '...' to load the page fresh. You'll run into all kinds of issues with back/forward at that point.

php - How to organize country/state/city browsing in MVC - Stack Overf...

php ajax codeigniter codeigniter-routing
Rectangle 27 0

I'm facing a similar challenge. I don't know whether it's the case with you but in my case we need to be sure that the cities that are entered are really the existing ones. Later on in the project we want to be able to collect entries that are in the same city, anywhere in the world. And those results need to be precise. So we can't have people entering Philadelphia and Philly as well. And we also want people to use the English names for cities and not the names in their own language.

I've found some public databases of countries, states and cities. For instance here: MaxMind. But it's a list of roughly 3M cities and I've found another one of more than 6M. I've set it up exactly the way you describe. Select the country, then get the cities in it via an AJAX call and fill the dropdown. It takes about 2 seconds for a country like the Netherlands but the loading is just not acceptable for China or Russia for instance. And the lists are huge and not that user friendly at all.

So I suppose it's better to let people just enter them in a textfield when it's not that important that the cities really all match. We're looking at the Google Maps API right now to solve our problem.

Thanks abel for your nice suggestion. i have very near to a solution. as soon as i done with that, i will post it here. thanks once again.

php - Country/City/state validation - Stack Overflow

php jquery validation geocode
Rectangle 27 0

GeoDataSource World Cities Database (Gold Edition) March.2010

and more, there is even a basic and premium package.

May not be worthwhile if your looking for something free however because the free package only offers city names. The basic package is One Month - $149.95 One Year - $449.95

and the packages only get more expensive.

open source - PHP library with Countries, States and Cities - Stack Ov...

php open-source map
Rectangle 27 0

Ok I have got a way to do that:

RewriteRule ^bylocation/([-a-z_]+)(?:/([-a-z_]+)(?:/([-a-z_]+))?)?/?$ location.php?country=$1&state=$2&city=$3 [NC,L,QSA]

This single rule can take care, instead of three rules.

php - How to rewrite these urls for country, state, city? - Stack Over...

php apache mod-rewrite
Rectangle 27 0

If I understand your question correctly, you have to set the relations between your models: Address BelongsTo City, City BelongsTo State, State BelongsTo Country. Then when you retrieve an address from the database, it will also automatically retrieve the state and the country, unless you specify otherwise.

Here is some info on model associations: http://book.cakephp.org/view/1039/Associations-Linking-Models-Together (you didn't say what version of CakePHP you're using so I linked to the latest one).

php - Some issue with the country, state and city dropdown in cakephp ...

php mysql cakephp
Rectangle 27 0

SQL queries will give you a set of results with a fixed number of columns. Your example has a variable number of columns (multiple city counts) so this won't work.

You can use COUNT and GROUP BY in the SQL to get something like

Country   State    Citiescount
Canada    state1      4
Canada    state2      3
USA       state2      2

etc, but you will have duplicates in the left hand column(s).

SELECT country, state, COUNT(cities)
    FROM address_base
GROUP BY country, state

To get rid of the duplicates, loop over it to make an multidimensional array doing something like

$countries = array();
foreach ($results as $row) {
    if (!isset($countries[$row->country])) {
        $countries[$row->country] = array();
    }
    $countries[$row->country][$row->state] = $row->citiescount;
}

Alternatively, you can just echo the stuff instead. You can either get all the results in one go like this and loop over the whole set, or you can break it into smaller queries and do one per country or one per state. Be warned, however, that putting SQL in loops kills kittens (and DB performance) :).

@Matt...I have tried group by ...as it used used with aggregate functions...doesn't help much in achieving my target display. Moreover, two cities can have same name but different states in US..., I tried Group By zip-codes....but i found that a zip-code of US can be the same in mexico. This creates a problem for me. Therefore i dropped that route.

GROUP BY should not cause a problem with duplicate values, as long as you get the clauses in the right order and include all of them. In the example above, I put country first, so you will get things grouped by that, then by state within the countries (one row for each state, even if the name is the same, as long as they are in different countries). I'm a bit confused as to what you are ultimately counting though. What do the numbers in brackets after the city names signify?

the number in the parenthesis after the city names gives me the total number of same city listed under the state..e.g:- in the above sample city 'apple' appear twice under the same city so - (2). This is what i am counting.

Grouping cities, states and countries in MYSQL PHP - Stack Overflow

php mysql multidimensional-array group-by
Rectangle 27 0

$group
$addToSet
$push

In basic JSON notation for the rest of the people:

db.country.aggregate([
    { "$group": { 
        "_id": {
            "country": "$country",
            "state": "$state"
        },
        "cities": { 
            "$addToSet": {
                "city": "$city",
                "_coords": "$_coords"
            }
        }
    }},
    { "$group": {
        "_id": "$_id.country",
        "states": {
            "$addToSet": {
                "state": "$_id.state",
                "cities": "$cities"
            }
        }
    }}       
])

And in PHP notation for you:

$collection->aggregate(
    array(
        array(
            '$group' => array(
                 '_id' => array(
                     'country' => 'country',
                     'state' => '$state'
                 ),
                 '$cities' => array(
                     '$addToSet' => array(
                         'city' => '$city',
                         '_coords' => '$_coords'
                      )
                 )
            )
        ),
        array(
            '$group' => array(
                '_id' => '$_id.country',
                'states' => array(
                    '$addToSet' => array(
                         'state' => '$_id.state',
                         'cities' => '$cities'                                  
                     )              
                )              
            )
        )
    )
);

But seriously, learn how to use json_decode. JSON is pretty much the "lingua franca" for general data structure representation, not to detract from YAML or simplified XML or others. It really is not hard to translate these things into a native language representation, especially when many libraies exist to do so.

php - Aggregate by country, state and city - Stack Overflow

php database mongodb nosql
Rectangle 27 0

This is tricky because by default google places will look up locations nearby the center of the map, regardless the suggestions in the dropdown.

So you must find the first suggestion from the dropdown, document.querySelector('.pac-item') - extract the location and use geocoder to lookup the latlng for that location.

Code for extracting the location :

function extractLocation(item) {
    var text = item.innerText || item.textContent;
    var upper = text.toUpperCase();
    var result='';
    for (var i=0;i<text.length;i++) {
        if (text[i]==upper[i]) {
            result+=' ';
        }
        result+=text[i];
    }
    return result;
}

On searchbox enter, select the first suggestion, extract the location, lookup latlng by geocoder and place marker :

input.onkeyup = function(e) {
   var code = (e.keyCode ? e.keyCode : e.which);
   var places = searchBox.getPlaces();
   if (code == 13 && places!=[]) {
     var firstSuggestion = document.querySelector('.pac-item');
     var query = extractLocation(firstSuggestion);
     geocoder.geocode({"address":query }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          clearMarkers();   
          var latLng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
          var marker = new google.maps.Marker({
             map: map,
             title: results[0].address_components[0].long_name,
             position: latLng,
          });
          markers.push(marker);
          map.setCenter(latLng);
          map.setZoom(10);
       }
     });
   } 
}

javascript - how to auto fill state and country by name of city in goo...

javascript php jquery google-maps google-maps-api-3
Rectangle 27 0

$result = mysql_query('SELECT Country, State, City From Address_Base ORDER BY Country, State, City') or die(mysql_error());

$countries = array();

// fetch results and build multidimensional array of city counts
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
    if(isset($countries[$row['Country']][$row['State']][$row['City']])){
        $countries[$row['Country']][$row['State']][$row['City']] += 1;
    } else{
        $countries[$row['Country']][$row['State']][$row['City']] = 1;
    }
}

// loop over all countries
foreach($countries as $country => $states){
    echo $country, PHP_EOL, '{'; // output country start

    // loop over all states
    foreach($states as $state => $cities){
        echo $state, ' - '; // output state start

        $cityCounts = array();
        foreach($cities as $city => $count){
            $cityCounts[] = $city.' ('.$count.')'; // add all city counts to array
        }

        // implode all city counts and output it
        echo implode(', ', $cityCounts);

        // output new line
        echo PHP_EOL;
    }

    // output country end
    echo PHP_EOL, '}';
}

@Tede: It keeps a counter for the city. If the array index with the city name exists it will increase the counter by one, otherwise the counter will start with 1.

Shef...thanks for replying...When i use this line: $countries[$row['Country']][$row['State']][$row['City']] += 1 ...it gives me an error: 'Undefined index'. removing the increment '+' , i am able to achieve all that i am targeting except the count of same cities in a state. Another thing that i find interesting is the way you have coded for the dynamic multidimensional array creation. I am glad to see it but i am not able to understand it. I searched the net a lot but there isn't much. Which book do i refer to or would you find some time to explain it for me?

@Tede: Undefined index is not an error, it's just a warning, ignore it. I built the multidimensional array based on the columns of your database. You can read about arrays on php.net docs. Or you can google it. If there is a line of code which is hard to understand for you, then let me know.

i have read about arrays and i understand that we use '=>' to define the keys and the values...but when we use this line of code... $countries[$row['Country']][$row['State']][$row['City']] += 1; i find it hard to understand, that's why i asked....Could you please explain this line?

Grouping cities, states and countries in MYSQL PHP - Stack Overflow

php mysql multidimensional-array group-by
Rectangle 27 0

You can create a drop-down list with laravel using the Form class:

echo Form::select('country', array('US' => 'United States', 'UK' => 'United Kingdom'));

php - How to add country, state and city select field in laravel forms...

php jquery ajax laravel
Rectangle 27 0

Also take into account, that there are cities which have the same name but are located in separate countries. Riga is a capital city of Latvia and also Riga is in USA, Michigan.

php - What's better? Countries, States and Cities on DataBase or not? ...

php mysql data integrity
Rectangle 27 0

If I was betting, I suspect the problem is that you are returning way too many rows, and what you need to use is a cascacading dropdown. Searching on 'javascript cascading dropdrown" will show lots of examples, for jquery and other populate script libraries.

If you understand "cascading dropdowns" you will know what you need to change - I'm going to assume jquery for simplicity. The idea is to simply serve the web page initially with only top level (country) SELECT populated. They, via a jquery event handling on country SELECT changing, you make the AJAX call to you server to collect the "states" when they select USA or provinces when then select Canada, etc. You then populate the "State/region" SELECT from this and do likewise for each level of cascading dropdown.

JQuery (and other script libraries) have everthing you need to make this simple -- If you don't use a script library -- take the time to learn JQuery immediately -- It will be some of the best time you ever spend learning about website development. JQuery is very widely used for good reason.

Thank you, will I need to change the structure of the tables to minimise the stress on the sql side as well as using javascript cascading drop drown? or by changing just the code be sufficient?

php - We have designed a Country, State, City Drop-down function on ou...

php mysql sql sql-server database